这是用户在 2024-8-28 14:46 为 https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#executing-test-cases 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

Robot Framework User Guide
机器人框架用户指南

Version 7.0.1 版本7.0.1

Copyright © 2008-2015 Nokia Networks
版权所有© 2008-2015诺基亚网络
Copyright © 2016- Robot Framework Foundation
版权所有© 2016-机器人框架基金会

Table of Contents 目录

1   Getting started 1入门

1.1   Introduction 1.1介绍

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中添加的。本用户指南仍然主要讨论创建测试、测试数据和测试库,但在创建任务时也适用相同的概念。

1.1.1   Why Robot Framework?
1.1.1为什么是机器人框架?

  • Enables easy-to-use tabular syntax for creating test cases in a uniform way.
    支持易于使用的表格语法,以统一的方式创建测试用例
  • Provides ability to create reusable higher-level keywords from the existing keywords.
    提供从现有关键字创建可重用的高级关键字的能力。
  • Provides easy-to-read result reports and logs in HTML format.
    以HTML格式提供易于阅读的结果报告日志
  • Is platform and application independent.
    独立于平台和应用程序。
  • Provides a simple library API for creating customized test libraries which can be implemented natively with Python.
    提供了一个简单的库API,用于创建自定义的测试库,这些库可以用Python本地实现。
  • Provides a command line interface and XML based output files for integration into existing build infrastructure (continuous integration systems).
    提供一个命令行界面和基于XML的输出文件,用于集成到现有的构建基础设施(持续集成系统)中。
  • Provides support for testing web applications, rest APIs, mobile applications, running processes, connecting to remote systems via Telnet or SSH, and so on.
    提供对测试Web应用程序、其余API、移动的应用程序、运行进程、通过Telnet或SSH连接到远程系统等的支持。
  • Supports creating data-driven test cases.
    支持创建数据驱动的测试用例
  • Has built-in support for variables, practical particularly for testing in different environments.
    内置变量支持,特别适用于不同环境下的测试。
  • Provides tagging to categorize and select test cases to be executed.
    提供标签来分类和选择要执行的测试用例。
  • Enables easy integration with source control: test suites are just files and directories that can be versioned with the production code.
    实现与源代码控制的轻松集成:测试套件只是可以与生产代码进行版本控制的文件和目录。
  • Provides test-case and test-suite -level setup and teardown.
    提供测试用例测试套件级别的设置和拆卸。
  • The modular architecture supports creating tests even for applications with several diverse interfaces.
    模块化架构支持创建测试,即使是具有多种不同接口的应用程序。

1.1.2   High-level architecture
1.1.2高层架构

Robot Framework is a generic, application and technology independent framework. It has a highly modular architecture illustrated in the diagram below.
Robot Framework是一个通用的、独立于应用和技术的框架。它具有高度模块化的架构,如下图所示。

src/GettingStarted/architecture.png

Robot Framework architecture
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启动时,它处理数据,执行测试用例并生成日志和报告。核心框架不知道任何关于被测目标的信息,与它的交互由处理。库可以直接使用应用程序接口,也可以使用低级测试工具作为驱动程序。

1.1.3   Screenshots 1.1.3屏幕截图

Following screenshots show examples of the test data and created reports and logs.
以下屏幕截图显示了测试数据以及创建的报告日志的示例。

src/GettingStarted/testdata_screenshots.png

Test case file 测试用例文件

src/GettingStarted/screenshots.png

Reports and logs 报告和日志

1.1.4   Getting more information
1.1.4获取更多信息

Project pages 项目页面

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上。

Mailing lists 邮件列表

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邮件列表,可以在其中询问和搜索更多信息。邮件列表档案对所有人开放(包括搜索引擎),每个人都可以自由加入这些列表。只有列表成员可以发送邮件,但是,为了防止垃圾邮件,新用户会受到审核,这意味着在您的第一封邮件通过之前可能需要一点时间。不要害怕把问题发送到邮件列表,但要记住如何以聪明的方式提问

robotframework-users
General discussion about all Robot Framework related issues. Questions and problems can be sent to this list. Used also for information sharing for all users.
关于所有Robot Framework相关问题的一般讨论。问题和疑问可以发送到这个列表。也用于所有用户的信息共享。
robotframework-announce
An announcements-only mailing list where only moderators can send messages. All announcements are sent also to the robotframework-users mailing list so there is no need to join both lists.
一个只有公告的邮件列表,只有版主可以发送消息。所有公告也会发送到robotframework-users邮件列表,因此无需加入两个列表。
robotframework-devel 机器人框架开发公司
Discussion about Robot Framework development.
讨论机器人框架的开发。

1.3   Installation instructions
1.3安装说明

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

1.3.1   Python installation
1.3.1 Python安装

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、JythonIronPython,你可以使用Robot Framework 4.1.3

Installing Python on Linux
在Linux上安装Python

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发行版通常默认使用用户安装来避免此类问题,但用户也可以自己决定使用虚拟环境

Installing Python on Windows
在Windows上安装Python

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

Installing Python on macOS
在macOS上安装Python

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 installation PyPy安装

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 --versionpypy 3--version

Note 注意

Using Robot Framework with PyPy is officially supported only on Linux.
在PyPy中使用Robot Framework仅在Linux上得到官方支持。

Configuring 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安装目录以及piprobot等命令的安装目录添加到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,请执行以下步骤:

  1. Find 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.
    设置下找到环境变量。有影响整个系统的变量,也有只影响当前用户的变量。修改前者需要管理员权限,但修改后者通常就足够了。
  2. Select 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不存在,请单击“新建”。
  3. Add both the Python installation directory and the Scripts directory under the installation directory into PATH.
    将Python安装目录和安装目录下的Python目录都添加到PATH
  4. Exit the dialog with Ok to save the changes.
    单击“OK”退出对话框以保存更改。
  5. Start a new command prompt for the changes to take effect.
    启动新的命令提示符以使更改生效。

1.3.2   Installing using pip
1.3.2使用pip安装

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安装的文档,以了解如何单独安装它。

Running pip command
运行pip命令

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命令运行。您可能需要在您的环境中使用上面解释的其他一些方法。

Installing and uninstalling Robot Framework
安装和卸载Robot Framework

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

1.3.3   Installing from source
1.3.3从源代码安装

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获取更多细节。

1.3.4   Verifying installation
1.3.4安装

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)

1.3.5   Virtual environments
1.3.5虚拟环境

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包安装在特定系统或应用程序的隔离位置,而不是将所有包安装到同一个全局位置。它们有两个主要用例:

  • Install packages needed by different projects into their own environments. This avoids conflicts if projects need different versions of same packages.
    将不同项目所需的软件包安装到他们自己的环境中。这避免了项目需要相同包的不同版本时的冲突。
  • Avoid installing everything under the global Python installation. This is especially important on Linux where the global Python installation may be used by the distribution itself and messing it up can cause severe problems.
    避免在全局Python安装下安装所有内容。这一点在Linux上尤其重要,因为全局Python安装可能由发行版本身使用,如果将其弄乱,可能会导致严重的问题。

1.4   Demonstrations 1.4示威

There are several demo projects that introduce Robot Framework and help getting started with it.
有几个演示项目介绍了Robot Framework,并帮助您开始使用它。

Quick Start Guide 快速入门指南
Introduces the most important features of Robot Framework and acts as an executable demo.
介绍Robot Framework最重要的功能,并作为可执行的演示。
Robot Framework demo 机器人框架演示
Simple example test cases. Demonstrates also creating custom test libraries.
简单的测试用例示例。还演示如何创建自定义测试库。
Web testing demo Web测试演示
Demonstrates how to create tests and higher level keywords. The system under test is a simple web page that is tested using SeleniumLibrary.
演示如何创建测试和更高级别的关键字。被测系统是一个使用SeleniumLibrary测试的简单网页。
ATDD with Robot Framework
ATDD与机器人框架
Demonstrates how to use Robot Framework when following Acceptance Test Driven Development (ATDD) process.
演示如何在遵循验收测试驱动开发(ATDD)过程时使用Robot Framework。

2   Creating test data 2创建测试数据

2.1   Test data syntax 2.1测试数据语法

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的整体测试数据语法。下面的部分将解释如何实际创建测试用例,测试套件等等。虽然这一部分主要使用术语测试,但在创建任务时也适用相同的规则。

2.1.1   Files and directories
2.1.1文件和目录

The hierarchical structure for arranging test cases is built as follows:
用于安排测试用例的层次结构构建如下:

  • Test cases are created in suite files.
    测试用例在套件文件中创建。
  • A test case file automatically creates a test suite containing the test cases in that file.
    测试用例文件自动创建包含该文件中的测试用例的测试套件
  • A directory containing test case files forms a higher-level test suite. Such a suite directory has suites created from test case files as its child test suites.
    包含测试用例文件的目录构成了更高级别的测试套件。这样的套件目录将从测试用例文件创建的套件作为其子测试套件。
  • A test suite directory can also contain other test suite directories, and this hierarchical structure can be as deeply nested as needed.
    测试套件目录还可以包含其他测试套件目录,并且此分层结构可以根据需要进行深度嵌套。
  • Test suite directories can have a special initialization file configuring the created test suite.
    测试套件目录可以有一个特殊的初始化文件来配置所创建的测试套件。

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。

2.1.2   Test data sections 2.1.2试验数据章节

Robot Framework data is defined in different sections, often also called tables, listed below:
Robot Framework数据定义在不同的部分中,通常也称为表,如下所示:

Different sections in data
数据中的不同部分
Section 部分 Used for 用于
Settings 设定值
2) Defining metadata for test suites and test cases.
2)为测试套件测试用例定义元数据。
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.
节标题可以本地化。有关支持的翻译,请参见翻译附录。

2.1.3   Supported file formats
2.1.3支持的文件格式

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格式。

Space separated format 空格分隔格式

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空格。如今,所有数据都按原样保存。

Pipe separated format 管道分隔格式

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 format reStructuredText格式

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中的新功能。

JSON format JSON格式

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用户设计的,并且不意味着手动编辑。它最重要的用例是:

  • Transferring data between processes and machines. A suite can be converted to JSON in one machine and recreated somewhere else.
    在过程和机器之间传输数据。一个套件可以在一台机器上转换为JSON,然后在其他地方重新创建。
  • Saving a suite, possibly a nested suite, constructed from normal Robot Framework data into a single JSON file that is faster to parse.
    将从普通Robot Framework数据构建的套件(可能是嵌套套件)保存到单个JSON文件中,这样可以更快地解析。
  • Alternative data format for external tools generating tests or tasks.
    用于生成测试或任务的外部工具的替代数据格式。

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频道上开始讨论。

Converting suite to JSON 将套件转换为JSON

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

Creating suite from JSON 从JSON创建套件

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文件可能更容易,如下节所述。

Executing JSON files 执行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扩展名,则需要配置解析哪些文件

Adjusting suite source 调整套件来源

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_jsonTestSuite.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')
JSON structure JSON结构

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模式文件中。

2.1.4   Rules for parsing the data
2.1.4解析数据的规则

Ignored data 忽略的数据

When Robot Framework parses the test data files, it ignores:
当Robot Framework解析测试数据文件时,它会忽略:

  • All data before the first test data section.
    第一个测试数据部分之前的所有数据。
  • Data in the Comments section.
    评论部分中的数据。
  • All empty rows. 全部为空行。
  • All empty cells at the end of rows when using the pipe separated format.
    使用竖线分隔格式时,行末尾的所有单元格为空。
  • All single backslashes (\) when not used for escaping.
    不用于转义时,所有单反斜杠(\)。
  • All characters following the hash character (#), 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输出中可见的信息,请将其放置到测试用例或套件的文档或其他元数据中,或者使用内置关键字LogComment将其记录下来。

Escaping 逸出

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}通常可用于转义。不同的逃逸机制将在下面的章节中讨论。

Escaping special characters
转义特殊字符

The backslash character can be used to escape special characters so that their literal values are used.
反斜杠字符可用于转义特殊字符,以便使用它们的文字值。

Escaping special characters
转义特殊字符
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}
Forming escape sequences 形成转义序列

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.
反斜杠字符还允许创建特殊的转义序列,这些转义序列被识别为在测试数据中很难或不可能创建的字符。

Escape sequences 转义序列
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,如果需要,必须显式转换为字节字符串。例如,可以分别使用BuiltInString库中的Convert To StringEncode 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(太大的值)的结果分别为xAXU 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

Handling empty values 处理空值

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 |
Handling spaces 装卸空间

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 spaces examples 逃逸空间示例
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}变量通常会使测试数据更容易理解。当需要多个空格时,它与扩展变量语法结合使用特别方便。

Dividing data to several rows
将数据划分为多行

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

2.1.5   Localization 2.1.5本地化

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.
本节介绍如何激活语言,支持哪些内置语言,如何创建自定义语言文件以及如何贡献新的翻译。

Enabling languages 使能语言

Using command line option
使用命令行选项

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.
出于向后兼容性的原因,并支持部分翻译,英语总是自动激活。未来的版本可能允许禁用它。

Pre-file configuration 预文件配置

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选项全局启用语言。

Custom language files 自定义语言文件

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类以及所有内置语言定义。

Contributing translations
贡献翻译

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频道。

2.1.6   Style 2.1.6风格

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语法非常灵活,但有一些通常推荐的约定:

  • Four space indentation. 四个空格缩进。
  • Four spaces between keywords and arguments, settings and their values, and so on. In some cases, most notable in the Settings and Variables sections and when using the data-driven style, it makes sense to align values and use more than four spaces, but using less is seldom a good idea.
    在关键字和参数、设置和它们的值等之间使用四个空格。在某些情况下,最值得注意的是在设置和变量部分以及使用数据驱动样式时,对齐值并使用四个以上的空格是有意义的,但使用较少的空格很少是一个好主意。
  • Global variables using capital letters like ${EXAMPLE} and local variables using lower-case letters like ${example}.
    全局变量使用大写字母,如${EXAMPLE};局部变量使用小写字母,如${example}
  • Consistency within a single file and preferably within the whole project.
    在单个文件中保持一致性,最好是在整个项目中保持一致性。

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代码格式化器来强制执行这些约定。

2.2   Creating test cases 2.2创建测试用例

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用于测试自动化以外的其他自动化目的时,建议创建任务而不是测试。任务语法的大部分与测试语法相同,创建任务一节中解释了它们的区别。

2.2.1   Test case syntax 2.2.1测试用例语法

Basic syntax 基本语法

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开头的测试。

Settings in the Test Case section
测试用例部分中的设置

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.
测试用例也可以有自己的设置。设置名称始终位于第二列中,关键字通常位于第二列中,其值位于后续列中。设置名称周围有方括号,以将其与关键字区分开来。下面列出了可用的设置,并在本节后面进行了说明。

[Documentation] [文件]
Used for specifying a test case documentation.
用于指定测试用例文档
[Setup], [Teardown]
[设置][拆除]
Specify test setup and teardown.
指定测试设置和拆卸
[Tags] [标签]
Used for tagging test cases.
用于标记测试用例
[Template] [模板]
Specifies the template keyword to use. The test itself will contain only data to use as arguments to that keyword.
指定要使用的模板关键字。测试本身将只包含用作该关键字的参数的数据。
[Timeout] [超时]
Used for setting a test case timeout. Timeouts are discussed in their own 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!

2.2.2   Using arguments 2.2.2使用参数

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 )生成的文档中也可以获得相同的信息。

Positional arguments 位置参数

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 DirectoryCopy File。它们的参数被指定为pathsource、destination,这意味着它们分别接受一个和两个参数。最后一个关键字NoOperation fromBuiltIn不带参数。

*** Test Cases ***
Example
    Create Directory    ${TEMPDIR}/stuff
    Copy File    ${CURDIR}/file.txt    ${TEMPDIR}/stuff
    No Operation

Default values 默认值

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

Variable number of arguments
数目可变的参数

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 FilesJoin Paths关键字分别具有参数*pathsbase,*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

Named arguments 命名参数

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中的关键字参数完全相同。

Basic syntax 基本语法

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调用该关键字,则参数arg1arg2将获得其默认值,但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=valueARG=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=值|位置|,不起作用。命名参数的相对顺序无关紧要。

Named arguments with variables
带变量的命名参数

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.
如果关键字需要接受并传递任何命名参数,则必须将其更改为接受自由命名参数。有关可以向前传递位置参数和命名参数的包装器关键字版本,请参见自由命名参数示例

Escaping named arguments syntax
转义命名参数语法

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的参数,则不需要转义,但因为它使情况更加明确,所以它可能仍然是一个好主意。

Where named arguments are supported
支持命名参数的地方

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关键字显式使用仅位置参数

Named arguments example 命名参数示例

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}

Free named arguments 自由命名参数

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}都是有效的,只要使用的变量存在。一个额外的限制是自由参数名称必须总是字符串。

Examples 示例

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}

Named-only arguments 仅命名参数

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}

Arguments embedded to keyword names
嵌入到关键字名称的参数

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.
一种完全不同的指定参数的方法是将它们嵌入到关键字名称中。测试库关键字用户关键字都支持此语法。

2.2.3   Failures 2.2.3故障

When test case fails 测试用例失败时

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.
如果测试用例使用的任何关键字失败,则测试用例失败。通常这意味着停止执行该测试用例,执行可能的测试拆卸,然后从下一个测试用例继续执行。如果不希望停止测试执行,也可以使用特殊的可持续故障

Error messages 错误消息

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.

2.2.4   Test case name and documentation
2.2.4测试用例名称和文档

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.
重要的是测试用例有清晰的描述性名称,在这种情况下,它们通常不需要任何文档。如果测试用例的逻辑需要文档化,这通常意味着测试用例中的关键字需要更好的名称,并且需要增强,而不是添加额外的文档。最后,元数据(如上面最后一个示例中的环境和用户信息)通常可以使用标记更好地指定。

2.2.5   Tagging test cases 2.2.5标记测试用例

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本身对它们没有特殊意义。标签至少可用于以下目的:

  • They are shown in test reports, logs and, of course, in the test data, so they provide metadata to test cases.
    它们显示在测试报告日志中,当然还有测试数据中,因此它们为测试用例提供元数据。
  • Statistics about test cases (total, passed, failed and skipped) are automatically collected based on them.
    测试用例的统计数据(总的,通过的,失败的和跳过的)会根据它们自动收集。
  • They can be used to include and exclude as well as to skip test cases.
    它们可以用来包含和排除测试用例,也可以用来跳过测试用例。

There are multiple ways how to specify tags for test cases explained below:
有多种方法可以为下面解释的测试用例指定标签:

Test Tags setting in the Settings section
设置部分中的测试标记设置
All tests in a test case file with this setting always get specified tags. If this setting is used in a suite initialization file, all tests in child suites get these tags.
具有此设置的测试用例文件中的所有测试始终获得指定的标记。如果在套件初始化文件中使用此设置,则子套件中的所有测试都将获得这些标记。
[Tags] setting with each test case
[Tags]每个测试用例的设置
Tests get these tags in addition to tags specified using the Test Tags setting. The [Tags] setting also allows removing tags set with Test Tags by using the -tag syntax.
除了使用“测试标记”设置指定的标记外,测试还获取这些标记。[Tags]设置还允许通过使用-tag语法删除使用Test Tags设置的标签。
--settag command line option
--settag命令行选项
All tests get tags set with this option in addition to tags they got elsewhere.
所有测试除了在其他地方获得标记外,还获得使用此选项设置的标记。
Set Tags, Remove Tags, Fail and Pass Execution keywords
设置标签删除标签失败通过执行关键字
These BuiltIn keywords can be used to manipulate tags dynamically during the test execution.
这些BuiltIn关键字可用于在测试执行期间动态地操作标记。

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中的新语法。

Deprecation of Force Tags and Default Tags
强制标签默认标签的弃用

Prior to Robot Framework 6.0, tags could be specified to tests in the Setting section using two different settings:
在Robot Framework 6.0之前,可以使用两种不同的设置为设置部分中的测试指定标记:

Force Tags 力标签
All tests unconditionally get these tags. This is exactly the same as Test Tags nowadays.
所有测试都无条件获得这些标签。这与今天的测试标签完全相同。
Default Tags 默认货签
All tests get these tags by default. If a test has [Tags], it will not get these tags.
默认情况下,所有测试都获得这些标记。如果一个测试有[Tags],它将不会得到这些标签。

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

Reserved tags 保留标签

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-failurerobot:recursive-continue-on-failure
Used for enabling the continue-on-failure mode.
用于启用故障时继续模式
robot:stop-on-failure and robot:recursive-stop-on-failure
robot:stop-on-failurerobot:recursive-stop-on-failure
Used for disabling the continue-on-failure mode.
用于禁用故障时继续模式
robot:skip-on-failure
Mark test to be skipped if it fails.
如果测试失败,则标记跳过测试。
robot:skip
Mark test to be unconditionally skipped.
无条件跳过标记测试。
robot:exclude
Mark test to be unconditionally excluded.
无条件排除标记测试。
robot:private
Mark keyword to be private.
将关键字标记为私有
robot:no-dry-run
Mark keyword not to be executed in the dry run mode.
将关键字标记为在空运行模式下不执行。
robot:exit
Added to tests automatically when execution is stopped gracefully.
正常停止执行时自动添加到测试中。
robot:flatten
Enable flattening keyword during execution time.
在执行期间启用扁平化关键字。

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:*命令行选项显式包含时,将显示它们。

2.2.6   Test setup and teardown
2.2.6测试设置和拆卸

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.
测试套件可以有自己的设置和拆卸。套件设置在该测试套件中的任何测试用例或子测试套件之前执行,类似地,套件拆卸在它们之后执行。

2.2.7   Test templates 2.2.7测试模板

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.
模板关键字可以接受普通的位置参数和命名参数,也可以接受嵌入到关键字名称中的参数。与其他设置不同,无法使用变量定义模板。

Basic usage 基本用法

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 with embedded arguments
带有嵌入参数的模板

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.
在模板中使用嵌入式参数的主要好处是参数名被显式指定。当使用普通参数时,通过命名包含参数的列可以达到相同的效果。下一节中的数据驱动样式示例对此进行了说明。

Templates with FOR loops
带有FOR循环的模板

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

Templates with IF/ELSE structures
IF/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

2.2.8   Different test case styles
2.2.8不同的测试用例风格

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.
编写测试用例有几种不同的方式。描述某种工作流的测试用例可以以关键字驱动或行为驱动的风格编写。数据驱动样式可以用于测试具有不同输入数据的相同工作流。

Keyword-driven style 关键字驱动风格

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测试)是由几个关键字及其可能的参数构造的。它们的正常结构是,首先系统进入初始状态(在有效登录示例中打开登录页面),然后对系统进行操作(输入名称输入密码提交凭据),最后验证系统是否按预期运行(欢迎页面应该打开)。

Data-driven style 数据驱动风格

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}

Behavior-driven style 行为驱动风格

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开头的关键字描述。如果步骤具有多个操作,则可以使用以AndBut开头的关键字。

*** 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
Ignoring Given/When/Then/And/But prefixes
忽略Given/When/Then/And/But前缀

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.
如果未找到与全名匹配的关键字,则在搜索匹配关键字时删除前缀GivenWhenThenAndBut。这对用户关键字和库关键字都有效。例如,在上面的例子中,Given登录页面是打开的,可以实现为带有或不带有Given这个词的用户关键字。忽略前缀还允许使用具有不同前缀的相同关键字。例如,欢迎页面应该打开也可以用作和欢迎页面应该打开

Note 注意

These prefixes can be localized. See the Translations appendix for supported translations.
这些前缀可以本地化。有关支持的翻译,请参见翻译附录。

Embedding data to keywords
将数据嵌入关键字

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.
在编写具体示例时,能够将实际数据传递给关键字实现是很有用的。用户关键字通过允许将参数嵌入到关键字名称中来支持这一点。

2.3   Creating tasks 2.3创建任务

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增加了对自动化任务的官方支持,而不仅仅是测试。在大多数情况下,创建任务的工作方式与创建测试的工作方式相同,唯一真实的区别在于术语。任务也可以像测试用例一样组织成套件

2.3.1   Task syntax 2.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.
将测试和任务放在同一个文件中是错误的。

2.4   Creating test suites 2.4创建测试套件

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测试用例在测试用例文件中创建,这些文件可以组织到目录中。这些文件和目录创建了一个层次化的测试套件结构。创建任务时也适用相同的概念,但术语不同。

2.4.1   Suite files 2.4.1套件文件

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:
设置部分中的以下设置可用于自定义套件:

Name 名称
Used for setting a custom suite name. The default name is created based on the file or directory name.
用于设置自定义套件名称。默认名称基于文件或目录名创建。
Documentation 文件
Used for specifying a suite documentation.
用于指定套件文档
Metadata 元数据
Used for setting free suite metadata as name-value pairs.
用于将可用套件元数据设置为名称-值对。
Suite Setup, Suite Teardown
套件设置套件拆卸
Specify suite setup and teardown.
指定套件设置和拆卸

Note 注意

Setting names are case-insensitive, but the format used above is recommended.
设置名称不区分大小写,但建议使用上述格式。

2.4.2   Suite directories 2.4.2套件目录

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:
当执行测试目录时,它包含的文件和目录将被递归处理,如下所示:

  • Files and directories with names starting with a dot (.) or an underscore (_) are ignored.
    名称以点(开头的文件和目录)或下划线(_)将被忽略。
  • Directories with the name CVS are ignored (case-sensitive).
    名为CVS的目录将被忽略(区分大小写)。
  • Files in supported file formats are processed.
    处理支持的文件格式的文件。
  • Other files are ignored. 其他文件将被忽略。

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.
如果被处理的文件或目录不包含任何测试用例,则会默默忽略它(将消息写入系统日志),并继续处理。

Suite initialization files
套件初始化文件

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.
初始化文件的主要用途是指定测试套件相关的设置,类似于套件文件,但也可以设置一些测试用例相关的设置。下面将解释如何在初始化文件中使用不同的设置。

Name, Documentation, Metadata, Suite Setup, Suite Teardown
名称文档元数据套件设置套件拆卸
These suite specific settings work the same way in suite initialization files as in suite files.
这些套件特定设置在套件初始化文件中的工作方式与套件文件中的工作方式相同。
Test Tags 测试标签
Specified tags are unconditionally set to all tests in all suite files this directory contains, recursively. New in Robot Framework 6.1. The deprecated Force Tags needs to be used with older versions.
指定的标记被无条件地递归地设置到该目录包含的所有套件文件中的所有测试。机器人框架6.1中的新功能。弃用的Force Tags需要与旧版本一起使用。
Test Setup, Test Teardown, Test Timeout
测试设置测试拆除测试超时
Set the default value for test setup/teardown or test timeout to all test cases this directory contains. Can be overridden on lower level. Notice that keywords used as setups and teardowns must be available in test case files where tests using them are. Defining keywords in the initialization file itself is not enough.
将测试设置/拆除或测试超时的默认值设置为此目录包含的所有测试用例。可以在较低级别上被覆盖。请注意,用作设置和拆卸的关键字必须在使用它们的测试所在的测试用例文件中可用。在初始化文件本身中定义关键字是不够的。
Task Setup, Task Teardown, Task Tags, Task Timeout
任务设置任务分解任务标记任务分解
Aliases for Test Setup, Test Teardown, Test Tags and Test Timeout, respectively, that can be used when creating tasks, not tests.
分别用于测试设置测试拆卸测试标记测试任务的别名,可在创建任务(而非测试)时使用。
Default Tags, Test Template
默认标签测试模板
Not supported in initialization files.
初始化文件中不支持。
*** 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

2.4.3   Suite name 2.4.3套房名称

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 TestsMy_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.robot02__more_tests.robot分别创建测试套件Some TestsMore 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选项覆盖顶级套件的名称。

2.4.4   Suite documentation
2.4.4套件文档

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选项从命令行覆盖顶级套件的文档。

2.4.5   Free suite metadata
2.4.5自由套件元数据

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选项进行设置。

2.4.6   Suite setup and teardown
2.4.6套件安装和拆卸

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.
要作为设置或拆除执行的关键字的名称可以是一个变量。通过在命令行中将关键字名称作为变量,这有助于在不同的环境中进行不同的设置或拆卸。

2.5   Using test libraries 2.5使用测试库

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.
测试库包含那些最低级别的关键字,通常称为库关键字,它们实际上与被测系统交互。所有的测试用例总是使用一些库中的关键字,通常是通过更高级别的用户关键字。本节解释如何使用测试库以及如何使用它们提供的关键字。创建测试库将在单独的一节中描述。

2.5.1   Importing libraries
2.5.1数据库

Test libraries are typically imported using the Library setting, but it is also possible to use the Import Library keyword.
测试库通常使用Library设置导入,但也可以使用ImportLibrary关键字。

Using 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.
可以在套件文件资源文件套件初始化文件中导入测试库。在所有这些情况下,导入库中的所有关键字都可以在该文件中使用。对于资源文件,这些关键字也可以在使用它们的其他文件中使用。

Using 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

2.5.2   Specifying library to import
2.5.2要导入的对象库

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关键字导入的,这些方法的工作方式都是相同的。

Using library name 使用库名称

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.
这种方法的最大好处是,当模块搜索路径已经配置好(通常使用自定义启动脚本)时,普通用户不需要考虑库实际安装的位置。缺点是,要将您自己的库(可能非常简单)放入搜索路径中,可能需要一些额外的配置。

Using physical path to library
使用库的物理路径

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类实现的库必须位于与类同名的模块中

2.5.3   Setting custom name to library
2.5.3设置库的自定义名称

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:
库名称显示在测试日志中关键字名称之前,如果多个关键字具有相同的名称,则必须使用它们,以便关键字名称以库名称为前缀。库名称通常从实现它的模块或类名获得,但在某些情况下需要更改它:

  • There is a need to import the same library several times with different arguments. This is not possible otherwise.
    需要使用不同的参数多次导入同一个库。否则这是不可能的。
  • The library name is inconveniently long.
    这个库的名称太长了,不方便。
  • You want to use variables to import different libraries in different environments, but refer to them with the same name.
    您希望使用变量在不同的环境中导入不同的库,但使用相同的名称引用它们。
  • The library name is misleading or otherwise poor. In this case, changing the actual name is, of course, a better solution.
    库名称具有误导性或不好。在这种情况下,更改实际名称当然是更好的解决方案。

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。旧的语法继续工作,但它被认为是过时的,最终将被删除。

2.5.4   Standard libraries 2.5.4标准库

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库是特殊的,因为它是自动使用的,因此它的关键字总是可用的。其他标准库需要以与任何其他库相同的方式导入,但不需要安装它们。

Normal standard libraries
正规标准库

The available normal standard libraries are listed below with links to their documentations:
下面列出了可用的常规标准库及其文档链接:

Remote library 远程库

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.
有关此概念的更多信息,请参见单独的远程库接口部分。

2.5.5   External libraries 2.5.5外部图书馆

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开源社区已经实现了几个通用库,如SeleniumLibrarySwingLibrary,它们没有与核心框架打包在一起。可以从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.
不同的外部库可以有完全不同的机制来安装和使用它们。有时候,它们可能还需要单独安装一些其他依赖项。所有库都应该有清晰的安装和使用文档,并且最好能够自动化安装过程。

2.6   Variables 2.6变量

2.6.1   Introduction 2.6.1引言

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:
变量是有用的,例如,在这些情况下:

  • When strings change often in the test data. With variables you only need to make these changes in one place.
    当字符串在测试数据中经常变化时。对于变量,你只需要在一个地方进行这些更改。
  • When creating system-independent and operating-system-independent test data. Using variables instead of hard-coded strings eases that considerably (for example, ${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)。这也方便了本地化测试,本地化测试通常涉及使用不同的字符串运行相同的测试。
  • When there is a need to have objects other than strings as arguments for keywords. This is not possible without variables.
    当需要使用字符串以外的对象作为关键字的参数时。没有变量,这是不可能的。
  • When different keywords, even in different test libraries, need to communicate. You can assign a return value from one keyword to a variable and pass it as an argument to another.
    当不同的关键字,即使在不同的测试库,需要沟通。您可以将一个关键字的返回值赋给一个变量,并将其作为参数传递给另一个关键字。
  • When values in the test data are long or otherwise complicated. For example, ${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}中所示。

2.6.2   Using variables 2.6.2使用变量

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的字母字符、数字、下划线和空格,甚至是使用扩展变量语法的要求。

Scalar variable syntax 标量变量语法

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}是可用的,并且分别被分配给字符串Helloworld,那么这两个示例测试用例是等效的。

*** 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:
最后,当这个测试数据被执行时,不同的关键字接收参数,如下所述:

  • KW 1 gets a string Hello, world!
    KW 1得到一个字符串Hello,world!
  • KW 2 gets an object stored to variable ${OBJ}
    KW 2获取存储到变量${OBJ}的对象
  • KW 3 gets a string I said "Hello, world!"
    KW 3得到一个字符串我说“你好,世界!"
  • KW 4 gets a string You said "Hi, terra!"
    KW 4得到一个字符串你说“嗨,泰拉!"

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}),因为这样值就可以按原样使用。

List variable syntax 列表变量语法

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'.
Using list variables with other data
将列表变量与其他数据一起使用

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}
Using list variables with settings
将列表变量与设置一起使用

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

Dictionary variable syntax
字典变量语法

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]等用法成为可能。

Using dictionary variables with other data
将字典变量与其他数据一起使用

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}
Using dictionary variables with settings
将字典变量与设置一起使用

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

Accessing list and dictionary items
目录和字典条目

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中被弃用。

Accessing sequence items 序列项

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之前,仅支持包含列表、元组或其他被视为类似列表的对象的变量的项和切片访问。现在支持所有序列,包括字符串和字节。

Accessing individual dictionary items
搜索单个词典条目

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}!
Nested item access 嵌套项访问

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}

Environment variables 环境变量

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中新增了对指定默认值的支持。

2.6.3   Creating variables 2.6.3创建变量

Variables can spring into existence from different sources.
变量可以从不同的来源出现。

Variable section 变截面

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部分。变量部分很方便,因为它们允许在与其余测试数据相同的地方创建变量,并且所需的语法非常简单。它们的主要缺点是值总是字符串,并且不能动态创建。如果这两种情况都有问题,可以使用变量文件

Creating scalar variables
创建标量变量

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 创建列表变量

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
Creating dictionary variables
创建字典变量

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]

Creating variable name based on another variable
基于另一个变量创建变量名

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 file 变量文件

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.
变量文件是创建不同类型变量的最强大的机制。可以使用它们将变量分配给任何对象,并且它们还可以动态创建变量。在资源和变量文件一节中解释了变量文件的语法和如何使用变量文件。

Setting variables in command line
在命令行中设置变量

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:7272robot

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
从关键字返回值

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关键字,如下一节所述。

Assigning scalar variables
标量变量

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}
Assigning variables with item values
使用项值检查变量

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'}
Creating variable name based on another variable
基于另一个变量创建变量名

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
Assigning list variables 列表变量

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会自动验证该值是否为列表或类似列表,存储的变量值将是从返回值创建的新列表。当分配给标量变量时,不会验证返回值,并且存储的值将与返回的对象完全相同。

Assigning dictionary variables
字典变量

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}。这些字典也是有序的,但是如果原始字典没有排序,那么结果的顺序是任意的。

Assigning multiple variables
多元变量

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.
    分别具有值123${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.
如果返回的列表中的值多于或少于要分配的标量变量,则为错误。此外,只允许一个列表变量,字典变量只能单独赋值。

Automatically logging assigned variable value
自动记录分配的变量值

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 syntax
VAR语法

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 VariableSet Test VariableSet Suite VariableSet Global Variable,但它也可以用来代替CatenateCreate ListCreate Dictionary

Creating scalar variables
创建标量变量

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
Creating list and dictionary variables
创建列表和字典变量

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
Scope 范围

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(在当前测试中可用)、ASKTEST的别名)、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
Creating variables conditionally
有条件地创建变量

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
Creating variable name based on another variable
基于另一个变量创建变量名

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

Using Set Test/Suite/Global Variable keywords
使用Set Test/Suite/Global Variable关键字

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 VariableSet Suite VariableSet 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使用返回值设置局部变量。

2.6.4   Built-in variables 2.6.4内置变量

Robot Framework provides some built-in variables that are available automatically.
Robot Framework提供了一些自动可用的内置变量。

Operating-system variables
操作系统变量

Built-in variables related to the operating system ease making the test data operating-system-agnostic.
与操作系统相关的内置变量使测试数据与操作系统无关变得容易。

Available operating-system-related built-in variables
可用的与操作系统相关的内置变量
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

Number variables 数量变量

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.
也可以分别使用0b0o0x前缀从二进制、八进制和十六进制值创建整数。语法不区分大小写。

*** Test Cases ***
Example
    Should Be Equal    ${0b1011}    ${11}
    Should Be Equal    ${0o10}      ${8}
    Should Be Equal    ${0xff}      ${255}
    Should Be Equal    ${0B1010}    ${0XA}

Boolean and None/null variables
Boolean和None/null变量

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}是等价的。

Space and empty variables
空间和空变量

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

Automatic variables 自动变量

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库中的关键字动态更改某些值。

Available automatic variables
可用自动变量
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 TagsRemove 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 ${OPTIONS}[key] and ${OPTIONS.key}. Available options:
字典暴露命令行选项。字典键与命令行选项匹配,可以像${OPTIONS}[key]${OPTIONS.key}一样访问。可用选项:

  • ${OPTIONS.exclude} (--exclude)
    ${OPTIONS.exclude}--exclude
  • ${OPTIONS.include} (--include)
    ${OPTIONS.include}--include
  • ${OPTIONS.skip} (--skip)
    ${OPTIONS.skip}--skip
  • ${OPTIONS.skip_on_failure} (--skiponfailure)
    ${OPTIONS.skip_on_failure}--skiponfailure

New in RF 5.0. More options can be exposed later.
RF 5.0中的新功能。更多的选择可以稍后公布。

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})已经可用。但是,这些自动变量中的可能变量在导入时尚未解析。

2.6.5   Variable priorities and scopes
2.6.5可变优先事项和范围

Variables coming from different sources have different priorities and are available in different scopes.
来自不同来源的变量具有不同的优先级,并且在不同的作用域中可用。

Variable priorities 可变优先事项

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}很特殊,因为它在测试数据处理期间已经被替换。

Variable scopes 可变范围

Depending on where and how they are created, variables can have a global, test suite, test case or local scope.
根据变量创建的位置和方式,变量可以具有全局、测试套件、测试用例或局部作用域。

Global 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.
建议对所有全局变量使用大写字母。

Test suite scope 测试套件范围

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.
由于这些变量在使用它们的测试套件中可以被认为是全局的,因此建议也使用大写字母。

Test case scope 测试用例范围

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.
测试用例作用域中的变量在某种程度上也是全局的。因此,通常建议也使用大写字母。

Local scope 局部作用域

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.
建议在局部变量中使用小写字母。

2.6.6   Advanced variable features
2.6.6高级可变特性

Extended variable syntax 扩展变量语法

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:
当执行此测试数据时,关键字获取参数,如下所述:

  • KW 1 gets string Robot
    KW 1获得字符串机器人
  • KW 2 gets string Robot eats Cucumber
    KW 2获取字符串机器人吃黄瓜
  • KW 3 gets string two
    KW 3获得字符串2

The extended variable syntax is evaluated in the following order:
扩展变量语法按以下顺序计算:

  1. The variable is searched using the full variable name. The extended variable syntax is evaluated only if no matching variable is found.
    使用完整的变量名搜索变量。只有在找不到匹配的变量时,才计算扩展变量语法。
  2. The name of the base variable is created. The body of the name consists of all the characters after the opening { 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]})的基变量分别为OBBLOGDICTIONARY
  3. A variable matching the body is searched. If there is no match, an exception is raised and the test case fails.
    搜索与正文匹配的变量。如果没有匹配项,则引发异常,测试用例失败。
  4. The expression inside the curly brackets is evaluated as a Python expression, so that the base variable name is replaced with its value. If the evaluation fails because of an invalid syntax or that the queried attribute does not exist, an exception is raised and the test fails.
    大括号内的表达式被计算为Python表达式,因此基变量名被替换为它的值。如果由于语法无效或查询的属性不存在而导致计算失败,则会引发异常,测试失败。
  5. The whole extended variable is replaced with the value returned from the evaluation.
    整个扩展变量被替换为从计算返回的值。

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.
请注意,尽管abs(number)比number更受推荐。abs__()在普通Python代码中,使用${abs(number)}不起作用。这是因为变量名必须在扩展语法的开头。像这样在测试数据中使用__xxx__方法已经有点问题了,通常最好将这种逻辑移到测试库中。

Extended variable syntax works also in list variable context. If, for example, an object assigned to a variable ${EXTENDED} has an attribute attribute that contains a list as a value, it can be used as a list variable @{EXTENDED.attribute}.
扩展变量语法也适用于列表变量上下文中。例如,如果分配给变量${EXTENDED}的对象具有包含列表作为值的属性,则它可以用作列表变量@{EXTENDED.attribute}

Extended variable assignment
扩充变量赋值

It is possible to set attributes of objects stored to scalar variables using keyword return values and a variation of the extended variable syntax. Assuming we have variable ${OBJECT} from the previous examples, attributes could be set to it like in the example below.
可以使用关键字返回值扩展变量语法的变体来设置存储到标量变量的对象的属性。假设我们从前面的例子中得到了变量${OBJECTIVE},可以像下面的例子那样将属性设置为它。

*** Test Cases ***
Example
    ${OBJECT.name} =    Set Variable    New name
    ${OBJECT.new_attr} =    Set Variable    New attribute

The extended variable assignment syntax is evaluated using the following rules:
使用以下规则评估扩展变量赋值语法:

  1. The assigned variable must be a scalar variable and have at least one dot. Otherwise the extended assignment syntax is not used and the variable is assigned normally.
    赋值的变量必须是标量变量,并且至少有一个点。否则,不使用扩展赋值语法,变量将正常赋值。
  2. If there exists a variable with the full name (e.g. ${OBJECT.name} in the example above) that variable will be assigned a new value and the extended syntax is not used.
    如果存在具有全名的变量(例如,上面示例中的${RollT.name}),则该变量将被分配新值,并且不使用扩展语法。
  3. The name of the base variable is created. The body of the name consists of all the characters between the opening ${ and the last dot, for example, OBJECT in ${OBJECT.name} and foo.bar in ${foo.bar.zap}. As the second example illustrates, the base name may contain normal extended variable syntax.
    创建基变量的名称。名称的主体由开头${和最后一个点之间的所有字符组成,例如,${foot.name}的OBLOG${foo.bar.zap}foo.bar。如第二个示例所示,基名称可以包含普通的扩展变量语法。
  4. The name of the attribute to set is created by taking all the characters between the last dot and the closing }, for example, name in ${OBJECT.name}. If the name does not start with a letter or underscore and contain only these characters and numbers, the attribute is considered invalid and the extended syntax is not used. A new variable with the full name is created instead.
    要设置的属性的名称是通过采用最后一个点和结尾的}之间的所有字符创建的,例如,${name}中的name。如果名称不以字母或下划线开头,并且仅包含这些字符和数字,则该属性被视为无效,并且不使用扩展语法。而是创建一个具有全名的新变量。
  5. A variable matching the base name is searched. If no variable is found, the extended syntax is not used and, instead, a new variable is created using the full variable name.
    搜索与基名称匹配的变量。如果未找到变量,则不使用扩展语法,而是使用完整的变量名创建一个新变量。
  6. If the found variable is a string or a number, the extended syntax is ignored and a new variable created using the full name. This is done because you cannot add new attributes to Python strings or numbers, and this way the new syntax is also less backwards-incompatible.
    如果找到的变量是字符串或数字,则忽略扩展语法,并使用全名创建新变量。这样做是因为您不能向Python字符串或数字添加新属性,并且这样新语法也较少向后不兼容。
  7. If all the previous rules match, the attribute is set to the base variable. If setting fails for any reason, an exception is raised and the test fails.
    如果前面的所有规则都匹配,则将属性设置为基变量。如果设置因任何原因失败,则会引发异常,测试将失败。

Note 注意

Unlike when assigning variables normally using return values from keywords, changes to variables done using the extended assign syntax are not limited to the current scope. Because no new variable is created but instead the state of an existing variable is changed, all tests and keywords that see that variable will also see the changes.
与通常使用关键字的返回值分配变量不同,使用扩展赋值语法对变量进行的更改不限于当前范围。由于没有创建新变量,而是更改了现有变量的状态,因此所有看到该变量的测试和关键字也将看到这些更改。

Variables inside variables
变量中的变量

Variables are allowed also inside variables, and when this syntax is used, variables are resolved from the inside out. For example, if you have a variable ${var${x}}, then ${x} is resolved first. If it has the value name, the final value is then the value of the variable ${varname}. There can be several nested variables, but resolving the outermost fails, if any of them does not exist.
变量也允许在变量内部,当使用这种语法时,变量是从内到外解析的。例如,如果你有一个变量${var${x}},那么首先解析${x}。如果它具有值名称,则最终值是变量${varname}的值。可以有多个嵌套变量,但如果其中任何一个不存在,则解析最外层的变量将失败。

In the example below, Do X gets the value ${JOHN HOME} or ${JANE HOME}, depending on if Get Name returns john or jane. If it returns something else, resolving ${${name} HOME} fails.
在下面的示例中,Do X获取值${JOHN HOME}${JANE HOME},具体取决于Get Name返回的是john还是jane。如果返回其他内容,解析${${name} HOME}将失败。

*** Variables ***
${JOHN HOME}    /home/john
${JANE HOME}    /home/jane

*** Test Cases ***
Example
    ${name} =    Get Name
    Do X    ${${name} HOME}

Inline Python evaluation 内联Python评估

Variable syntax can also be used for evaluating Python expressions. The basic syntax is ${{expression}} i.e. there are double curly braces around the expression. The expression can be any valid Python expression such as ${{1 + 2}} or ${{['a', 'list']}}. Spaces around the expression are allowed, so also ${{ 1 + 2 }} and ${{ ['a', 'list'] }} are valid. In addition to using normal scalar variables, also list variables and dictionary variables support @{{expression}} and &{{expression}} syntax, respectively.

Main usages for this pretty advanced functionality are:

  • Evaluating Python expressions involving Robot Framework's variables (${{len('${var}') > 3}}, ${{$var[0] if $var is not None else None}}).
    评估涉及Robot Framework变量的Python表达式(${{len('${var <$')> 3}}${{$var[0] if $var is not None else None}})。
  • Creating values that are not Python base types (${{decimal.Decimal('0.11')}}, ${{datetime.date(2019, 11, 5)}}).
  • Creating values dynamically (${{random.randint(0, 100)}}, ${{datetime.date.today()}}).
  • Constructing collections, especially nested collections (${{[1, 2, 3, 4]}}, ${{ {'id': 1, 'name': 'Example', 'children': [7, 9]} }}).
  • Accessing constants and other useful attributes in Python modules (${{math.pi}}, ${{platform.system()}}).

This is somewhat similar functionality than the extended variable syntax discussed earlier. As the examples above illustrate, this syntax is even more powerful as it provides access to Python built-ins like len() and modules like math. In addition to being able to use variables like ${var} in the expressions (they are replaced before evaluation), variables are also available using the special $var syntax during evaluation. The whole expression syntax is explained in the Evaluating expressions appendix.
这与前面讨论的扩展变量语法的功能有些类似。正如上面的例子所示,这种语法甚至更强大,因为它提供了对Python内置函数(如len())和模块(如math)的访问。除了能够在表达式中使用像${var}这样的变量(它们在计算之前被替换)之外,在计算期间还可以使用特殊的$var语法来使用变量。整个表达式语法在求值表达式附录中解释。

Tip 尖端

Instead of creating complicated expressions, it is often better to move the logic into a custom library. That eases maintenance, makes test data easier to understand and can also enhance execution speed.
与其创建复杂的表达式,不如将逻辑移到自定义库中。这简化了维护,使测试数据更容易理解,还可以提高执行速度。

Note 注意

The inline Python evaluation syntax is new in Robot Framework 3.2.
内联Python求值语法是Robot Framework 3.2中的新语法。

2.7   Creating user keywords
2.7创建用户关键字

Keyword sections are used to create new higher-level keywords by combining existing keywords together. These keywords are called user keywords to differentiate them from lowest level library keywords that are implemented in test libraries. The syntax for creating user keywords is very close to the syntax for creating test cases, which makes it easy to learn.
关键字部分用于通过将现有关键字组合在一起来创建新的更高级别的关键字。这些关键字称为用户关键字,以区别于测试库中实现的最低级别的库关键字。创建用户关键字的语法与创建测试用例的语法非常接近,这使其易于学习。

2.7.1   User keyword syntax
2.7.1用户关键字语法

Basic syntax 基本语法

In many ways, the overall user keyword syntax is identical to the test case syntax. User keywords are created in Keyword sections which differ from Test Case sections only by the name that is used to identify them. User keyword names are in the first column similarly as test cases names. Also user keywords are created from keywords, either from keywords in test libraries or other user keywords. Keyword names are normally in the second column, but when setting variables from keyword return values, they are in the subsequent columns.
在许多方面,整个user关键字语法与测试用例语法相同。用户关键字在关键字部分中创建,关键字部分与测试用例部分的区别仅在于用于识别它们的名称。用户关键字名称在第一列中,类似于测试用例名称。此外,用户关键字是从关键字创建的,无论是从测试库中的关键字还是其他用户关键字。关键字名称通常位于第二列中,但当从关键字返回值设置变量时,它们位于后续列中。

*** Keywords ***
Open Login Page
    Open Browser    http://host/login.html
    Title Should Be    Login Page

Title Should Start With
    [Arguments]    ${expected}
    ${title} =    Get Title
    Should Start With    ${title}    ${expected}

Most user keywords take some arguments. This important feature is used already in the second example above, and it is explained in detail later in this section, similarly as user keyword return values.
大多数用户关键字都有一些参数。这个重要的特性已经在上面的第二个例子中使用过了,它将在本节后面详细解释,类似于用户关键字返回值

User keywords can be created in suite files, resource files, and suite initialization files. Keywords created in resource files are available for files using them, whereas other keywords are only available in the files where they are created.
可以在套件文件资源文件套件初始化文件中创建用户关键字。在资源文件中创建的关键字可用于使用它们的文件,而其他关键字仅在创建它们的文件中可用。

Settings in the Keyword section
关键字部分中的设置

User keywords can have similar settings as test cases, and they have the same square bracket syntax separating them from keyword names. All available settings are listed below and explained later in this section.
用户关键字可以具有与测试用例类似的设置,并且它们具有相同的方括号语法将它们与关键字名称分开。下面列出了所有可用的设置,并在本节后面进行了说明。

[Documentation] [文件]
Used for setting a user keyword documentation.
用于设置用户文档的关键字。
[Tags] [标签]
Sets tags for the keyword.
设置关键字的标记
[Arguments] [争论]
Specifies user keyword arguments.
指定用户关键字参数
[Setup], [Teardown]
【设置】【拆卸】
Specify user keyword setup and teardown. [Setup] is new in Robot Framework 7.0.
指定用户关键字设置和拆卸[设置]是Robot Framework 7.0中的新功能。
[Timeout] [超时]
Sets the possible user keyword timeout. Timeouts are discussed in a section of their own.
设置可能的用户关键字超时超时将在它们自己的一节中讨论。
[Return] [返回]
Specifies user keyword return values. Deprecated in Robot Framework 7.0, the RETURN statement should be used instead.
指定用户关键字返回值。在Robot Framework 7.0中已弃用,应改用RETURN语句。

Note 注意

The format used above is recommended, but setting names are case-insensitive and spaces are allowed between brackets and the name. For example, [ TAGS ]:setting is valid.
建议使用上面使用的格式,但设置名称不区分大小写,并且允许在括号和名称之间使用空格。例如,[ TAGS ]:设置有效。

2.7.2   User keyword name and documentation
2.7.2用户关键字名称和文档

The user keyword name is defined in the first column of the Keyword section. Of course, the name should be descriptive, and it is acceptable to have quite long keyword names. Actually, when creating use-case-like test cases, the highest-level keywords are often formulated as sentences or even paragraphs.
用户关键字名称在Keyword部分的第一列中定义。当然,名称应该是描述性的,并且可以接受相当长的关键字名称。实际上,当创建类似用例的测试用例时,最高级别的关键字通常被公式化为句子甚至段落。

User keywords can have a documentation that is set with the [Documentation] setting. It supports same formatting, splitting to multiple lines, and other features as test case documentation. This setting documents the user keyword in the test data. It is also shown in a more formal keyword documentation, which the Libdoc tool can create from resource files. Finally, the first logical row of the documentation, until the first empty row, is shown as a keyword documentation in test logs.
用户关键字可以具有使用[Documentation]设置设置的文档。它支持与测试用例文档相同的格式、拆分为多行以及其他特性。此设置记录测试数据中的用户关键字。它还显示在一个更正式的关键字文档中,Libdoc工具可以从资源文件创建该文档。最后,文档的第一个逻辑行(直到第一个空行)在测试日志中显示为关键字documentation。

*** Keywords ***
One line documentation
    [Documentation]    One line documentation.
    No Operation

Multiline documentation
    [Documentation]    The first line creates the short doc.
    ...
    ...                This is the body of the documentation.
    ...                It is not shown in Libdoc outputs but only
    ...                the short doc is shown in logs.
    No Operation

Short documentation in multiple lines
    [Documentation]    If the short doc gets longer, it can span
    ...                multiple physical lines.
    ...
    ...                The body is separated from the short doc with
    ...                an empty line.
    No Operation

Sometimes keywords need to be removed, replaced with new ones, or deprecated for other reasons. User keywords can be marked deprecated by starting the documentation with *DEPRECATED*, which will cause a warning when the keyword is used. For more information, see the Deprecating keywords section.
有时关键字需要删除,替换为新的,或出于其他原因弃用。用户关键字可以通过以*DEPRECATED*开始文档来标记为已弃用,这将在使用关键字时引起警告。有关详细信息,请参阅弃用关键字部分。

Note 注意

Prior to Robot Framework 3.1, the short documentation contained only the first physical line of the keyword documentation.
在Robot Framework 3.1之前,短文档只包含关键字documentation的第一个物理行。

2.7.3   User keyword tags 2.7.3用户关键字标签

Both user keywords and library keywords can have tags. Similarly as when tagging test cases, there are two settings affecting user keyword tags:
用户关键字和库关键字都可以有标记。与标记测试用例时类似,有两个设置会影响用户关键字标记:

Keyword Tags setting in the Settings section
设置部分中的关键字标签设置
All keywords in a file with this setting always get specified tags.
具有此设置的文件中的所有关键字始终获得指定的标记。
[Tags] setting with each keyword
[标签]每个关键字的设置
Keywords get these tags in addition to possible tags specified using the Keyword Tags setting. The [Tags] setting also allows removing tags set with Keyword Tags by using the -tag syntax.
除了使用“关键字标签”设置指定的可能标签外,关键字还获取这些标签。[Tags]设置还允许使用-tag语法删除使用Keyword Tags设置的标签。
*** Settings ***
Keyword Tags       gui    html

*** Keywords ***
No own tags
    [Documentation]    Keyword has tags 'gui' and 'html'.
    No Operation

Own tags
    [Documentation]    Keyword has tags 'gui', 'html', 'own' and 'tags'.
    [Tags]    own    tags
    No Operation

Remove common tag
    [Documentation]    Test has tags 'gui' and 'own'.
    [Tags]    own    -html
    No Operation

Keyword tags can be specified using variables, the -tag syntax supports patterns, and so on, exactly as test case tags.
可以使用变量指定关键字标签,-tag语法支持模式等,与测试用例标签完全相同。

In addition to using the dedicated settings, keyword tags can be specified on the last line of the documentation with Tags: prefix so that tags are separated with a comma. For example, following two keywords get same three tags:
除了使用专用设置外,还可以在文档的最后一行使用Tags:prefix指定关键字标签,以便用逗号分隔标签。例如,以下两个关键字得到相同的三个标签:

*** Keywords ***
Settings tags using separate setting
    [Tags]    my    fine    tags
    No Operation

Settings tags using documentation
    [Documentation]    I have documentation. And my documentation has tags.
    ...                Tags: my, fine, tags
    No Operation

Keyword tags are shown in logs and in documentation generated by Libdoc, where the keywords can also be searched based on tags. The --removekeywords and --flattenkeywords commandline options also support selecting keywords by tag, and new usages for keywords tags are possibly added in later releases.
关键字标签显示在日志和Libdoc生成的文档中,其中关键字也可以基于标签进行搜索。--removekeywords--removekeywords命令行选项还支持按标记选择关键字,并且在以后的版本中可能会添加keywords标记的新用法。

Similarly as with test case tags, user keyword tags with the robot: prefix are reserved for special features by Robot Framework itself. Users should thus not use any tag with these prefixes unless actually activating the special functionality. Starting from Robot Framework 6.1, flattening keyword during execution time can be taken into use using reserved tag robot:flatten.
测试用例标签类似,带有robot:前缀的用户关键字标签由Robot Framework本身保留用于特殊功能。因此,用户不应该使用任何带有这些前缀的标签,除非实际激活特殊功能。从Robot Framework 6.1开始,可以使用保留标签robot:flatten来使用执行时的flattening关键字

Note 注意

Keyword Tags is new in Robot Framework 6.0. With earlier versions all keyword tags need to be specified using the [Tags] setting.
关键字标签是Robot Framework 6.0中的新功能。对于早期版本,所有关键字标签都需要使用[Tags]设置来指定。

Note 注意

The -tag syntax for removing common tags is new in Robot Framework 7.0.
用于删除公共标记的-tag语法是Robot Framework 7.0中的新语法。

2.7.4   User keyword arguments
2.7.4用户关键字参数

Most user keywords need to take some arguments. The syntax for specifying them is probably the most complicated feature normally needed with Robot Framework, but even that is relatively easy, particularly in most common cases. Arguments are normally specified with the [Arguments] setting, and argument names use the same syntax as variables, for example ${arg}.
大多数用户关键字需要带一些参数。指定它们的语法可能是Robot Framework通常需要的最复杂的功能,但即使是这样也相对容易,特别是在大多数常见情况下。参数通常使用[Arguments]设置指定,参数名称使用与变量相同的语法,例如${arg}

Positional arguments with user keywords
带有用户关键字的位置参数

The simplest way to specify arguments (apart from not having them at all) is using only positional arguments. In most cases, this is all that is needed.
指定参数的最简单方法(除了根本没有参数之外)是只使用位置参数。在大多数情况下,这就是所有需要的。

The syntax is such that first the [Arguments] setting is given and then argument names are defined in the subsequent cells. Each argument is in its own cell, using the same syntax as with variables. The keyword must be used with as many arguments as there are argument names in its signature. The actual argument names do not matter to the framework, but from users' perspective they should be as descriptive as possible. It is recommended to use lower-case letters in variable names, either as ${my_arg}, ${my arg} or ${myArg}.
语法是这样的:首先给出[Arguments]设置,然后在后续单元格中定义参数名称。每个参数都在自己的单元格中,使用与变量相同的语法。关键字必须与其签名中的参数名称一起使用。实际的参数名称对框架来说并不重要,但是从用户的角度来看,它们应该尽可能具有描述性。建议在变量名中使用小写字母,例如${my_arg}${my arg}${myArg}

*** Keywords ***
One Argument
    [Arguments]    ${arg_name}
    Log    Got argument ${arg_name}

Three Arguments
    [Arguments]    ${arg1}    ${arg2}    ${arg3}
    Log    1st argument: ${arg1}
    Log    2nd argument: ${arg2}
    Log    3rd argument: ${arg3}

Default values with user keywords
带有用户关键字的默认值

When creating user keywords, positional arguments are sufficient in most situations. It is, however, sometimes useful that keywords have default values for some or all of their arguments. Also user keywords support default values, and the needed new syntax does not add very much to the already discussed basic syntax.
当创建用户关键字时,位置参数在大多数情况下就足够了。然而,有时关键字为其部分或所有参数提供默认值是很有用的。此外,用户关键字支持默认值,所需的新语法不会对已经讨论过的基本语法增加太多。

In short, default values are added to arguments, so that first there is the equals sign (=) and then the value, for example ${arg}=default. There can be many arguments with defaults, but they all must be given after the normal positional arguments. The default value can contain a variable created on test, suite or global scope, but local variables of the keyword executor cannot be used. Default value can also be defined based on earlier arguments accepted by the keyword.
简而言之,默认值被添加到参数中,因此首先是等号(=),然后是值,例如${arg}=default。可以有许多参数带有默认值,但它们都必须在正常的位置参数之后给出。默认值可以包含在test、suite或global范围内创建的变量,但不能使用关键字executor的局部变量。默认值也可以根据关键字接受的早期参数定义。

Note 注意

The syntax for default values is space sensitive. Spaces before the = sign are not allowed, and possible spaces after it are considered part of the default value itself.
默认值的语法是空间敏感的。不允许在=号之前使用空格,并且在=号之后可能使用的空格将被视为默认值本身的一部分。

*** Keywords ***
One Argument With Default Value
    [Arguments]    ${arg}=default value
    [Documentation]    This keyword takes 0-1 arguments
    Log    Got argument ${arg}

Two Arguments With Defaults
    [Arguments]    ${arg1}=default 1    ${arg2}=${VARIABLE}
    [Documentation]    This keyword takes 0-2 arguments
    Log    1st argument ${arg1}
    Log    2nd argument ${arg2}

One Required And One With Default
    [Arguments]    ${required}    ${optional}=default
    [Documentation]    This keyword takes 1-2 arguments
    Log    Required: ${required}
    Log    Optional: ${optional}

 Default Based On Earlier Argument
    [Arguments]    ${a}    ${b}=${a}    ${c}=${a} and ${b}
    Should Be Equal    ${a}    ${b}
    Should Be Equal    ${c}    ${a} and ${b}

When a keyword accepts several arguments with default values and only some of them needs to be overridden, it is often handy to use the named arguments syntax. When this syntax is used with user keywords, the arguments are specified without the ${} decoration. For example, the second keyword above could be used like below and ${arg1} would still get its default value.
当一个关键字接受多个具有默认值的参数,并且其中只有一部分需要重写时,使用命名参数语法通常很方便。当此语法与用户关键字一起使用时,指定的参数不带${}装饰。例如,上面的第二个关键字可以像下面一样使用,并且${arg 1}仍然会获得其默认值。

*** Test Cases ***
Example
    Two Arguments With Defaults    arg2=new value

As all Pythonistas must have already noticed, the syntax for specifying default arguments is heavily inspired by Python syntax for function default values.
正如所有的Python爱好者都已经注意到的那样,指定默认参数的语法在很大程度上受到了Python函数默认值语法的启发。

Variable number of arguments with user keywords
具有用户关键字的参数数量可变

Sometimes even default values are not enough and there is a need for a keyword accepting variable number of arguments. User keywords support also this feature. All that is needed is having list variable such as @{varargs} after possible positional arguments in the keyword signature. This syntax can be combined with the previously described default values, and at the end the list variable gets all the leftover arguments that do not match other arguments. The list variable can thus have any number of items, even zero.
有时甚至默认值是不够的,需要一个接受可变数量参数的关键字。用户关键字也支持此功能。所需要的只是在关键字签名中可能的位置参数之后添加列表变量,如@{varargs}。这种语法可以与前面描述的默认值结合使用,在最后,list变量将获得所有不匹配其他参数的剩余参数。因此,列表变量可以有任意数量的项,甚至是零。

*** Keywords ***
Any Number Of Arguments
    [Arguments]    @{varargs}
    Log Many    @{varargs}

One Or More Arguments
    [Arguments]    ${required}    @{rest}
    Log Many    ${required}    @{rest}

Required, Default, Varargs
    [Arguments]    ${req}    ${opt}=42    @{others}
    Log    Required: ${req}
    Log    Optional: ${opt}
    Log    Others:
    FOR    ${item}    IN    @{others}
        Log    ${item}
    END

Notice that if the last keyword above is used with more than one argument, the second argument ${opt} always gets the given value instead of the default value. This happens even if the given value is empty. The last example also illustrates how a variable number of arguments accepted by a user keyword can be used in a for loop. This combination of two rather advanced functions can sometimes be very useful.
请注意,如果上面的最后一个关键字与多个参数一起使用,则第二个参数${opt}始终获取给定值而不是默认值。即使给定的值为空,也会发生这种情况。最后一个例子还说明了如何在for循环中使用user关键字接受的可变数量的参数。这两个相当高级的功能的组合有时会非常有用。

The keywords in the examples above could be used, for example, like this:
上面例子中的关键字可以这样使用:

*** Test Cases ***
Varargs with user keywords
    Any Number Of Arguments
    Any Number Of Arguments    arg
    Any Number Of Arguments    arg1    arg2    arg3   arg4
    One Or More Arguments    required
    One Or More Arguments    arg1    arg2    arg3   arg4
    Required, Default, Varargs    required
    Required, Default, Varargs    required    optional
    Required, Default, Varargs    arg1    arg2    arg3    arg4    arg5

Again, Pythonistas probably notice that the variable number of arguments syntax is very close to the one in Python.
同样,Pythonists可能会注意到变量个数语法与Python中的非常接近。

Free named arguments with user keywords
带有用户关键字的免费命名参数

User keywords can also accept free named arguments by having a dictionary variable like &{named} as the absolutely last argument. When the keyword is called, this variable will get all named arguments that do not match any positional argument or named-only argument in the keyword signature.
用户关键字也可以接受自由命名参数,方法是将字典变量(如&{named})作为绝对最后一个参数。当关键字被调用时,此变量将获取所有与关键字签名中的任何位置参数仅命名参数不匹配的命名参数

*** Keywords ***
Free Named Only
    [Arguments]    &{named}
    Log Many    &{named}

Positional And Free Named
    [Arguments]    ${required}    &{extra}
    Log Many    ${required}    &{extra}

Run Program
    [Arguments]    @{args}    &{config}
    Run Process    program.py    @{args}    &{config}

The last example above shows how to create a wrapper keyword that accepts any positional or named argument and passes them forward. See free named argument examples for a full example with same keyword.
上面的最后一个例子展示了如何创建一个包装器关键字,它接受任何位置或命名参数并将它们向前传递。请参阅自由命名参数示例,以获得具有相同关键字的完整示例。

Free named arguments support with user keywords works similarly as kwargs work in Python. In the signature and also when passing arguments forward, &{kwargs} is pretty much the same as Python's **kwargs.
使用用户关键字的自由命名参数支持与Python中的kwargs类似。在签名中以及向前传递参数时,&{kwargs}与Python的**kwargs几乎相同。

Named-only arguments with user keywords
带有用户关键字的仅命名参数

Starting from Robot Framework 3.1, user keywords support named-only arguments that are inspired by Python 3 keyword-only arguments. This syntax is typically used by having normal arguments after variable number of arguments (@{varargs}). If the keywords does not use varargs, it is possible to use just @{} to denote that the subsequent arguments are named-only:
从Robot Framework 3.1开始,用户关键字支持仅命名参数,这些参数受到Python 3仅关键字参数的启发。此语法通常通过变量数量的参数@{varargs})之后使用普通参数来使用。如果关键字不使用varargs,可以只使用@{}来表示后续参数是仅命名的:

*** Keywords ***
With Varargs
    [Arguments]    @{varargs}    ${named}
    Log Many    @{varargs}    ${named}

Without Varargs
    [Arguments]    @{}    ${first}    ${second}
    Log Many    ${first}    ${second}

Named-only arguments can be used together with positional arguments as well as with free named arguments. When using free named arguments, they must be last:
仅命名参数可以与位置参数以及自由命名参数一起使用。当使用自由命名参数时,它们必须是最后一个:

*** Keywords ***
With Positional
    [Arguments]    ${positional}    @{}    ${named}
    Log Many    ${positional}    ${named}

With Free Named
    [Arguments]    @{varargs}    ${named only}    &{free named}
    Log Many    @{varargs}    ${named only}    &{free named}

When passing named-only arguments to keywords, their order does not matter other than they must follow possible positional arguments. The keywords above could be used, for example, like this:
将仅命名参数传递给关键字时,它们的顺序无关紧要,只是必须跟在可能的位置参数之后。上面的关键字可以这样使用:

*** Test Cases ***
Example
    With Varargs    named=value
    With Varargs    positional    second positional    named=foobar
    Without Varargs    first=1    second=2
    Without Varargs    second=toka    first=eka
    With Positional    foo    named=bar
    With Positional    named=2    positional=1
    With Free Named    positional    named only=value    x=1    y=2
    With Free Named    foo=a    bar=b    named only=c    quux=d

Named-only arguments can have default values similarly as normal user keyword arguments. A minor difference is that the order of arguments with and without default values is not important.
普通用户关键字参数类似,仅命名参数可以具有默认值。一个微小的区别是,带和不带默认值的参数的顺序并不重要。

*** Keywords ***
With Default
    [Arguments]    @{}    ${named}=default
    Log Many    ${named}

With And Without Defaults
    [Arguments]    @{}    ${optional}=default    ${mandatory}    ${mandatory 2}    ${optional 2}=default 2    ${mandatory 3}
    Log Many    ${optional}    ${mandatory}    ${mandatory 2}    ${optional 2}    ${mandatory 3}

2.7.5   Embedding arguments into keyword name
2.7.5将参数嵌入到关键字名称中

The previous section explained how to pass arguments to keywords so that they are listed separately after the keyword name. Robot Framework has also another approach to pass arguments, embedding them directly to the keyword name, used by the second test below:
上一节解释了如何将参数传递给关键字,以便它们单独列在关键字名称之后。Robot Framework还有另一种传递参数的方法,将它们直接嵌入到关键字名称中,用于下面的第二个测试:

*** Test Cases ***
Normal arguments
    Select from list    cat

Embedded arguments
    Select cat from list

As the example illustrates, embedding arguments to keyword names can make the data easier to read and understand even for people without any Robot Framework experience.
如示例所示,将参数嵌入到关键字名称可以使数据更容易阅读和理解,即使对于没有任何Robot Framework经验的人也是如此。

Basic syntax 基本语法

The previous example showed how using a keyword Select cat from list is more fluent than using Select from list so that cat is passed to it as an argument. We obviously could implement Select cat from list as a normal keyword accepting no arguments, but then we needed to implement various other keywords like Select dog from list for other animals. Embedded arguments simplify this and we can instead implement just one keyword with name Select ${animal} from list and use it with any animal:
上一个例子展示了如何使用关键字Select cat from list比使用Select from list更流畅,以便cat作为参数传递给它。显然,我们可以实现从列表中选择猫作为一个普通的关键字接受没有参数,但我们需要实现各种其他关键字,如从列表中选择狗为其他动物。嵌入式参数简化了这一点,我们可以只实现一个名为Select ${animal} from list的关键字,并将其用于任何动物:

*** Test Cases ***
Embedded arguments
    Select cat from list
    Select dog from list

*** Keywords ***
Select ${animal} from list
    Open Page    Pet Selection
    Select Item From List    animal_list    ${animal}

As the above example shows, embedded arguments are specified simply by using variables in keyword names. The arguments used in the name are naturally available inside the keyword and they have different values depending on how the keyword is called. In the above example, ${animal} has value cat when the keyword is used for the first time and dog when it is used for the second time.
正如上面的例子所示,嵌入参数可以通过在关键字名称中使用变量来指定。name中使用的参数在关键字中自然可用,并且根据关键字的调用方式,它们具有不同的值。在上面的例子中,${animal}在第一次使用关键字时的值是cat,第二次使用时的值是dog

Starting from Robot Framework 6.1, it is possible to create user keywords that accept both embedded and "normal" arguments:
从Robot Framework 6.1开始,可以创建接受嵌入和“正常”参数的用户关键字:

*** Test Cases ***
Embedded and normal arguments
    Number of cats should be    2
    Number of dogs should be    count=3

*** Keywords ***
Number of ${animals} should be
    [Arguments]    ${count}
    Open Page    Pet Selection
    Select Items From List    animal_list    ${animals}
    Number of Selected List Items Should Be    ${count}

Other than the special name, keywords with embedded arguments are created just like other user keywords. They are also used the same way as other keywords except that spaces and underscores are not ignored in their names when keywords are matched. They are, however, case-insensitive like other keywords. For example, the Select ${animal} from list keyword could be used like select cow from list, but not like Select cow fromlist.
除了特殊名称之外,带有嵌入参数的关键字与其他用户关键字一样被创建。它们的使用方式也与其他关键字相同,只是在匹配关键字时不会忽略其名称中的空格和下划线。但是,它们与其他关键字一样不区分大小写。例如,从列表中选择${animal}关键字可以像从列表中选择奶牛一样使用,但不像从列表中选择奶牛

Embedded arguments do not support default values or variable number of arguments like normal arguments do. If such functionality is needed, normal arguments should be used instead. Passing embedded arguments as variables is possible, but that can reduce readability:
嵌入式参数不像普通参数那样支持默认值或可变数量的参数。如果需要这样的功能,则应该使用普通参数。将嵌入参数作为变量传递是可能的,但这会降低可读性:

*** Variables ***
${SELECT}        cat

*** Test Cases ***
Embedded arguments with variable
    Select ${SELECT} from list

*** Keywords ***
Select ${animal} from list
    Open Page    Pet Selection
    Select Item From List    animal_list    ${animal}

Embedded arguments matching wrong values
与错误值匹配的嵌入参数

One tricky part in using embedded arguments is making sure that the values used when calling the keyword match the correct arguments. This is a problem especially if there are multiple arguments and characters separating them may also appear in the given values. For example, Select Los Angeles Lakers in the following example matches Select ${city} ${team} so that ${city} contains Los and ${team} contains Angeles Lakers:
使用嵌入式参数的一个棘手部分是确保调用关键字时使用的值与正确的参数匹配。这是一个问题,特别是如果有多个参数,并且分隔它们的字符也可能出现在给定的值中。例如,以下示例中的Select洛杉矶湖人队Select ${city} ${team}匹配,以便${city}包含洛杉矶${team}包含洛杉矶湖人队

*** Test Cases ***
Example
    Select Chicago Bulls
    Select Los Angeles Lakers

*** Keywords ***
Select ${city} ${team}
    Log    Selected ${team} from ${city}.

An easy solution to this problem is surrounding arguments with double quotes or other characters not used in the actual values. This fixed example works so that cities and teams match correctly:
这个问题的一个简单解决方案是用双引号或其他在实际值中不使用的字符包围参数。这个固定的例子工作,使城市和球队正确匹配:

*** Test Cases ***
Example
    Select "Chicago" "Bulls"
    Select "Los Angeles" "Lakers"

*** Keywords ***
Select "${city}" "${team}"
    Log    Selected ${team} from ${city}.

This approach is not enough to resolve all conflicts, but it helps in common cases and is generally recommended. Another benefit is that it makes arguments stand out from rest of the keyword.
这种方法不足以解决所有冲突,但在常见情况下会有所帮助,并且通常被推荐。另一个好处是,它使参数从关键字的其余部分中脱颖而出。

The problem of arguments matching too much occurs often when creating keywords that ignore the given/when/then/and/but prefixes typically used in Behavior Driven Development (BDD). For example, ${name} goes home matches Given Janne goes home so that ${name} gets value Given Janne. Quotes around the argument, like in "${name}" goes home, resolve this problem easily.
当创建忽略行为驱动开发(BDD)中通常使用的给定/when/then/和/but前缀的关键字时,经常会出现参数匹配过多的问题。例如,${name} goes home匹配Given Janne goes home,因此${name}获取值Given Janne。引用周围的论点,就像在“${name}”回家,轻松解决这个问题。

An alternative solution for limiting what values arguments match is using custom regular expressions.
限制参数匹配的值的另一种解决方案是使用自定义正则表达式

Resolving conflicts 解决冲突

When using embedded arguments, it is pretty common that there are multiple keyword implementations that match the keyword that is used. For example, Execute "ls" with "lf" in the example below matches both of the keywords. It matching Execute "${cmd}" with "${opts}" is pretty obvious and what we want, but it also matches Execute "${cmd}" so that ${cmd} matches ls" with "-lh.
当使用嵌入参数时,通常会有多个关键字实现与所使用的关键字匹配。例如,在下面的示例中,执行“ls”和“lf”匹配这两个关键字。它匹配执行“${cmd}”和“${opts}”是非常明显的,也是我们想要的,但它也匹配执行“${cmd}”,以便${cmd}匹配ls”和“-lh”。

*** Settings ***
Library          Process

*** Test Cases ***
Automatic conflict resolution
    Execute "ls"
    Execute "ls" with "-lh"

*** Keywords ***
Execute "${cmd}"
    Run Process    ${cmd}    shell=True

Execute "${cmd}" with "${opts}"
    Run Process    ${cmd} ${opts}    shell=True

When this kind of conflicts occur, Robot Framework tries to automatically select the best match and use that. In the above example, Execute "${cmd}" with "${opts}" is considered a better match than the more generic Execute "${cmd}" and running the example thus succeeds without conflicts.
当这种冲突发生时,Robot Framework会尝试自动选择最佳匹配并使用它。在上面的示例中,执行“${cmd}”和“${opts}”被认为是比更通用的执行“${cmd}”更好的匹配,因此可以成功运行该示例而不会发生冲突。

It is not always possible to find a single match that is better than others. For example, the second test below fails because Robot Framework matches both of the keywords equally well. This kind of conflicts need to be resolved manually either by renaming keywords or by using custom regular expressions.
并不总是能够找到一个比其他人更好的匹配。例如,下面的第二个测试失败,因为Robot Framework与两个关键字匹配得同样好。这种冲突需要通过重命名关键字或使用自定义正则表达式手动解决。

*** Test Cases ***
No conflict
    Automation framework
    Robot uprising

Unresolvable conflict
    Robot Framework

*** Keywords ***
${type} Framework
    Should Be Equal    ${type}    Automation

Robot ${action}
    Should Be Equal    ${action}    uprising

Keywords that accept only "normal" arguments or no arguments at all are considered to match better than keywords accepting embedded arguments. For example, if the following keyword is added to the above example, Robot Framework used by the latter test matches it and the test succeeds:
只接受“普通”参数或根本不接受参数的关键字被认为比接受嵌入参数的关键字匹配得更好。例如,如果将以下关键字添加到上面的示例中,则后一个测试使用的Robot Framework与之匹配,并且测试成功:

*** Keywords ***
Robot Framework
    No Operation

Before looking which match is best, Robot Framework checks are some of the matching keywords implemented in the same file as the caller keyword. If there are such keywords, they are given precedence over other keywords. Alternatively, library search order can be used to control the order in which Robot Framework looks for keywords in resources and libraries.
在查看哪个匹配最好之前,Robot Framework检查的是与caller关键字在同一文件中实现的一些匹配关键字。如果有这样的关键字,它们将优先于其他关键字。或者,库搜索顺序可用于控制Robot Framework在资源和库中查找关键字的顺序。

Note 注意

Automatically resolving conflicts if multiple keywords with embedded arguments match is a new feature in Robot Framework 6.0. With older versions custom regular expressions explained below can be used instead.
自动解决冲突,如果多个关键字与嵌入参数匹配是一个新的功能,在机器人框架6.0。对于旧版本,可以使用下面解释的自定义正则表达式。

Using custom regular expressions
使用自定义正则表达式

When keywords with embedded arguments are called, the values are matched internally using regular expressions (regexps for short). The default logic goes so that every argument in the name is replaced with a pattern .*? that matches any string and tries to match as little as possible. This logic works fairly well normally, but as discussed above, sometimes keywords match wrong values and sometimes there are conflicts that cannot be resolved . A solution in these cases is specifying a custom regular expression that makes sure that the keyword matches only what it should in that particular context. To be able to use this feature, and to fully understand the examples in this section, you need to understand at least the basics of the regular expression syntax.
当调用带有嵌入参数的关键字时,使用正则表达式(简称regexp)在内部匹配值。默认逻辑是这样的,名称中的每个参数都被替换为一个模式匹配任何字符串并尝试尽可能少地匹配。这种逻辑在正常情况下工作得相当好,但是如上所述,有时关键字匹配错误的值,有时存在无法解决的冲突。在这些情况下,一个解决方案是指定一个自定义正则表达式,以确保关键字只匹配它在特定上下文中应该匹配的内容。为了能够使用这个特性,并完全理解本节中的示例,您至少需要了解正则表达式语法的基础知识。

A custom embedded argument regular expression is defined after the base name of the argument so that the argument and the regexp are separated with a colon. For example, an argument that should match only numbers can be defined like ${arg:\d+}.
自定义嵌入参数正则表达式定义在参数的基名称之后,以便用冒号分隔参数和regexp。例如,只能匹配数字的参数可以像${arg:\d+}这样定义。

Using custom regular expressions is illustrated by the following examples. Notice that the first one shows how the earlier problem with Select ${city} ${team} not matching Select Los Angeles Lakers properly can be resolved without quoting. That is achieved by implementing the keyword so that ${team} can only contain non-whitespace characters.
下面的示例说明了如何使用自定义正则表达式。请注意,第一个示例显示了Select ${city} ${team}Select洛杉矶湖人队不匹配的早期问题如何在不引用的情况下得到解决。这是通过实现关键字来实现的,以便${team}只能包含非空格字符。

*** Settings ***
Library          DateTime

*** Test Cases ***
Do not match whitespace characters
    Select Chicago Bulls
    Select Los Angeles Lakers

Match numbers and characters from set
    1 + 2 = 3
    53 - 11 = 42

Match either date or literal 'today'
    Deadline is 2022-09-21
    Deadline is today

*** Keywords ***
Select ${city} ${team:\S+}
    Log    Selected ${team} from ${city}.

${number1:\d+} ${operator:[+-]} ${number2:\d+} = ${expected:\d+}
    ${result} =    Evaluate    ${number1} ${operator} ${number2}
    Should Be Equal As Integers    ${result}    ${expected}

Deadline is ${date:(\d{4}-\d{2}-\d{2}|today)}
    IF    '${date}' == 'today'
        ${date} =    Get Current Date
    ELSE
        ${date} =    Convert Date    ${date}
    END
    Log    Deadline is on ${date}.
Supported regular expression syntax
支持的正则表达式语法

Being implemented with Python, Robot Framework naturally uses Python's re module that has pretty standard regular expressions syntax. This syntax is otherwise fully supported with embedded arguments, but regexp extensions in format (?...) cannot be used. If the regular expression syntax is invalid, creating the keyword fails with an error visible in test execution errors.
由于使用Python实现,Robot Framework自然使用Python的re模块,该模块具有非常标准的正则表达式语法。嵌入参数完全支持这种语法,但格式为(?...)的regexp扩展无法使用。如果正则表达式语法无效,则创建关键字失败,并在测试执行错误中显示错误。

Escaping special characters
转义特殊字符

Regular expressions use the backslash character (\) heavily both to form special sequences (e.g. \d) and to escape characters that have a special meaning in regexps (e.g. \$). Typically in Robot Framework data backslash characters need to be escaped with another backslash, but that is not required in this context. If there is a need to have a literal backslash in the pattern, then the backslash must be escaped like ${path:c:\\temp\\.*}.
正则表达式大量使用反斜杠字符(\)来形成特殊序列(例如\d)和转义在正则表达式中具有特殊含义的字符(例如\$)。通常在Robot Framework中,数据反斜杠字符需要用另一个反斜杠进行转义,但在此上下文中不需要。如果需要在模式中有一个文字反斜杠,那么反斜杠必须像${path:c:\\temp\\.*}那样转义.

Possible lone opening and closing curly braces in the pattern must be escaped like ${open:\{} and ${close:\}} or otherwise Robot Framework is not able to parse the variable syntax correctly. If there are matching braces like in ${digits:\d{2}}, escaping is not needed.
模式中可能单独的左花括号和右花括号必须像${open:\{}${close:\}}一样进行转义,否则Robot Framework无法正确解析变量语法。如果有像${digits:\d{2}}中那样的匹配大括号,则不需要转义。

Note 注意

Prior to Robot Framework 3.2, it was mandatory to escape all closing curly braces in the pattern like ${digits:\d{2\}}. This syntax is unfortunately not supported by Robot Framework 3.2 or newer and keywords using it must be updated when upgrading.
在Robot Framework 3.2之前,必须转义模式中的所有右花括号,如${digits:\d{2\}}。不幸的是,Robot Framework 3.2或更高版本不支持此语法,并且必须在升级时更新使用它的关键字。

Note 注意

Prior to Robot Framework 6.0, using literal backslashes in the pattern required double escaping them like ${path:c:\\\\temp\\\\.*}. Patterns using literal backslashes need to be updated when upgrading.
在Robot Framework 6.0之前,在模式中使用文字反斜杠需要像${path:c:\temp\.*}一样进行双转义.使用文字反斜杠的模式需要在升级时更新。

Using variables with custom embedded argument regular expressions
使用具有自定义嵌入参数正则表达式的变量

When embedded arguments are used with custom regular expressions, Robot Framework automatically enhances the specified regexps so that they match variables in addition to the text matching the pattern. For example, the following test case would pass using the keywords from the earlier example.
当嵌入参数与自定义正则表达式一起使用时,Robot Framework会自动增强指定的正则表达式,以便它们除了匹配模式的文本外还匹配变量。例如,下面的测试用例将使用前面示例中的关键字通过。

*** Variables ***
${DATE}    2011-06-27

*** Test Cases ***
Example
    Deadline is ${DATE}
    ${1} + ${2} = ${3}

A limitation of using variables is that their actual values are not matched against custom regular expressions. As the result keywords may be called with values that their custom regexps would not allow. This behavior is deprecated starting from Robot Framework 6.0 and values will be validated in the future. For more information see issue #4462.
使用变量的一个限制是,它们的实际值不能与自定义正则表达式匹配。因此,关键字可能会被调用,而其自定义regexp不允许使用这些值。从Robot Framework 6.0开始,此行为已被弃用,值将在将来进行验证。有关更多信息,请参阅问题#4462

Behavior-driven development example
行为驱动开发示例

A big benefit of having arguments as part of the keyword name is that it makes it easier to use higher-level sentence-like keywords when using the behavior-driven style to write tests. As the example below shows, this support is typically used in combination with the possibility to omit Given, When and Then prefixes in keyword definitions:
将参数作为关键字名称的一部分的一大好处是,当使用行为驱动风格编写测试时,它可以更容易地使用更高级别的类似于JavaScript的关键字。如下面的例子所示,这种支持通常与省略关键字定义中的Given,When和Then前缀的可能性结合使用:

*** Test Cases ***
Add two numbers
    Given I have Calculator open
    When I add 2 and 40
    Then result should be 42

Add negative numbers
    Given I have Calculator open
    When I add 1 and -2
    Then result should be -1

*** Keywords ***
I have ${program} open
    Start Program    ${program}

I add ${number 1} and ${number 2}
    Input Number    ${number 1}
    Push Button     +
    Input Number    ${number 2}
    Push Button     =

Result should be ${expected}
    ${result} =    Get Result
    Should Be Equal    ${result}    ${expected}

Note 注意

Embedded arguments feature in Robot Framework is inspired by how step definitions are created in the popular BDD tool Cucumber.
Robot Framework中的嵌入参数功能受到流行的BDD工具Cucumber中如何创建步骤定义的启发。

2.7.6   User keyword return values
2.7.6用户关键字返回值

Similarly as library keywords, also user keywords can return values. When using Robot Framework 5.0 or newer, the recommended approach is using the native RETURN statement. The old [Return] setting was deprecated in Robot Framework 7.0 and also BuiltIn keywords Return From Keyword and Return From Keyword If are considered deprecated.
与库关键字类似,用户关键字也可以返回值。使用Robot Framework 5.0或更高版本时,建议使用本机RETURN语句。旧的[Return]设置在Robot Framework 7.0中被弃用,内置关键字Return From KeywordReturn From Keyword If也被视为弃用。

Regardless how values are returned, they can be assigned to variables in test cases and in other user keywords.
无论如何返回值,都可以将它们赋给测试用例和其他用户关键字中的变量。

Using RETURN statement
使用RETURN语句

The recommended approach to return values is using the RETURN statement. It accepts optional return values and can be used with IF and inline IF structures. Its usage is easiest explained with examples:
返回值的推荐方法是使用RETURN语句。它接受可选的返回值,并可用于IF内联IF结构。它的用法最容易解释的例子:

*** Keywords ***
Return One Value
    [Arguments]    ${arg}
    [Documentation]    Return a value unconditionally.
    ...                Notice that keywords after RETURN are not executed.
    ${value} =    Convert To Upper Case    ${arg}
    RETURN    ${value}
    Fail    Not executed

Return Three Values
    [Documentation]    Return multiple values.
    RETURN    a    b    c

Conditional Return
    [Arguments]    ${arg}
    [Documentation]    Return conditionally.
    Log    Before
    IF    ${arg} == 1
        Log    Returning!
        RETURN
    END
    Log    After

Find Index
    [Arguments]    ${test}    ${items}
    [Documentation]    Advanced example involving FOR loop, inline IF and @{list} variable syntax.
    FOR    ${index}    ${item}    IN ENUMERATE    @{items}
        IF    $item == $test    RETURN    ${index}
    END
    RETURN    ${-1}

If you want to test the above examples yourself, you can use them with these test cases:
如果你想自己测试上面的例子,你可以使用这些测试用例:

*** Settings ***
Library           String

*** Test Cases ***
One return value
    ${ret} =    Return One Value    argument
    Should Be Equal    ${ret}    ARGUMENT

Multiple return values
    ${a}    ${b}    ${c} =    Return Three Values
    Should Be Equal    ${a}, ${b}, ${c}    a, b, c

Conditional return
    Conditional Return    1
    Conditional Return    2

Advanced
    @{list} =    Create List    foo    bar    baz
    ${index} =    Find Index    bar    ${list}
    Should Be Equal    ${index}    ${1}
    ${index} =    Find Index    non existing    ${list}
    Should Be Equal    ${index}    ${-1}

Note 注意

RETURN syntax is case-sensitive similarly as IF and FOR.
RETURN语法是区分大小写的,类似于IFFOR

Note 注意

RETURN is new in Robot Framework 5.0. Use approaches explained below if you need to support older versions.
RETURN是Robot Framework 5.0中的新功能。如果您需要支持旧版本,请使用下面解释的方法。

Using [Return] setting
使用[返回]设置

The [Return] setting defines what the keyword should return after it has been executed. Although it is recommended to have it at the end of keyword where it logically belongs, its position does not affect how it is used.
[返回]设置定义了关键字执行后应返回的内容。虽然建议将其放在逻辑上属于关键字的末尾,但其位置并不影响其使用方式。

An inherent limitation of the [Return] setting is that cannot be used conditionally. Thus only the first two earlier RETURN statement examples can be created using it.
[Return]设置的一个固有限制是不能有条件地使用。因此,只有前面的两个RETURN语句示例可以使用它创建。

*** Keywords ***
Return One Value
    [Arguments]    ${arg}
    ${value} =    Convert To Upper Case    ${arg}
    [Return]    ${value}

Return Three Values
    [Return]    a    b    c

Note 注意

The [Return] setting was deprecated in Robot Framework 7.0 and the RETURN statement should be used instead. If there is a need to support older Robot Framework versions that do not support RETURN, it is possible to use the special keywords discussed in the next section.
Robot Framework 7.0中不推荐使用[Return]设置,应改用RETURN语句。如果需要支持不支持RETURN的较旧的Robot Framework版本,可以使用下一节中讨论的特殊关键字。

Using special keywords to return
使用特殊关键字返回

BuiltIn keywords Return From Keyword and Return From Keyword If allow returning from a user keyword conditionally in the middle of the keyword. Both of them also accept optional return values that are handled exactly like with the RETURN statement and the [Return] setting discussed above.
内置关键字Return From KeywordReturn From Keyword If允许在关键字中间有条件地从用户关键字返回。它们都接受可选的返回值,这些返回值的处理方式与上面讨论的RETURN语句和[Return]设置完全相同。

The introduction of the RETURN statement makes these keywords redundant. Examples below contain same keywords as earlier RETURN examples but these ones are more verbose:
RETURN语句的引入使这些关键字变得多余。下面的示例包含与前面的RETURN示例相同的关键字,但这些示例更详细:

*** Keywords ***
Return One Value
    [Arguments]    ${arg}
    ${value} =    Convert To Upper Case    ${arg}
    Return From Keyword    ${value}
    Fail    Not executed

Return Three Values
    Return From Keyword        a    b    c

Conditional Return
    [Arguments]    ${arg}
    Log    Before
    IF    ${arg} == 1
        Log    Returning!
        Return From Keyword
    END
    Log    After

Find Index
    [Arguments]    ${test}    ${items}
    FOR    ${index}    ${item}    IN ENUMERATE    @{items}
        Return From Keyword If    $item == $test    ${index}
    END
    Return From Keyword    ${-1}

Note 注意

These keywords are effectively deprecated and the RETURN statement should be used unless there is a need to support also older versions than Robot Framework 5.0. There is no visible deprecation warning when using these keywords yet, but they will be loudly deprecated and eventually removed in the future.
这些关键字实际上已被弃用,除非需要支持Robot Framework 5.0之前的版本,否则应使用RETURN语句。在使用这些关键字时没有明显的弃用警告,但它们将被大声弃用,并最终在未来被删除。

2.7.7   User keyword setup and teardown
2.7.7用户关键字设置和拆除

A user keyword can have a setup and a teardown similarly as tests. They are specified using [Setup] and [Teardown] settings, respectively, directly to the keyword having them. Unlike with tests, it is not possible to specify a common setup or teardown to all keywords in a certain file.
测试类似,user关键字可以有setup和teardown。它们分别使用[Setup][Teardown]设置直接指定给具有它们的关键字。与测试不同,不可能为某个文件中的所有关键字指定公共设置或拆卸。

A setup and a teardown are always a single keyword, but they can themselves be user keywords executing multiple keywords internally. It is possible to specify them as variables, and using a special NONE value (case-insensitive) is the same as not having a setup or a teardown at all.
setup和teardown始终是一个关键字,但它们本身可以是在内部执行多个关键字的用户关键字。可以将它们指定为变量,并且使用特殊的NONE值(不区分大小写)与根本没有setup或teardown相同。

User keyword setup is not much different to the first keyword inside the created user keyword. The only functional difference is that a setup can be specified as a variable, but it can also be useful to be able to explicitly mark a keyword to be a setup.
用户关键字设置与创建的用户关键字中的第一个关键字没有太大区别。唯一的功能差异是设置可以被指定为变量,但它也可以用于显式地将关键字标记为设置。

User keyword teardowns are, exactly as test teardowns, executed also if the user keyword fails. They are thus very useful when needing to do something at the end of the keyword regardless of its status. To ensure that all cleanup activities are done, the continue on failure mode is enabled by default with user keyword teardowns the same way as with test teardowns.
用户关键字拆卸与测试拆卸一样,如果用户关键字失败,也会执行。因此,当需要在关键字末尾执行某些操作时,无论其状态如何,它们都非常有用。为了确保完成所有的清理活动,默认情况下,使用用户关键字teardowns的continue on失败模式与测试teardowns的方式相同。

*** Keywords ***
Setup and teardown
    [Setup]       Log    New in RF 7!
    Do Something
    [Teardown]    Log    Old feature.

Using variables
    [Setup]       ${SETUP}
    Do Something
    [Teardown]    ${TEARDOWN}

Note 注意

User keyword setups are new in Robot Framework 7.0.
用户关键字设置是Robot Framework 7.0中的新功能。

2.7.8   Private user keywords
2.7.8私人用户关键字

User keywords can be tagged with a special robot:private tag to indicate that they should only be used in the file where they are created:
用户关键字可以用一个特殊的robot:private标签来标记,以表明它们只应该在创建它们的文件中使用:

*** Keywords ***
Public Keyword
    Private Keyword

Private Keyword
    [Tags]    robot:private
    No Operation

Using the robot:private tag does not outright prevent using the keyword outside the file where it is created, but such usages will cause a warning. If there is both a public and a private keyword with the same name, the public one will be used but also this situation causes a warning.
使用robot:private标记并不能完全阻止在创建关键字的文件之外使用关键字,但这样的用法会导致警告。如果公共关键字和私有关键字都具有相同的名称,则将使用公共关键字,但这种情况也会导致警告。

Private keywords are included in spec files created by Libdoc but not in its HTML output files.
私有关键字包含在由Libdoc创建的spec文件中,但不包含在其HTML输出文件中。

Note 注意

Private user keywords are new in Robot Framework 6.0.
私有用户关键字是Robot Framework 6.0中的新功能。

2.8   Resource and variable files
2.8资源和变量文件

User keywords and variables in suite files and suite initialization files can only be used in files where they are created, but resource files provide a mechanism for sharing them. The high level syntax for creating resource files is exactly the same as when creating suite files and supported file formats are the same as well. The main difference is that resource files cannot have tests.
套件文件套件初始化文件中的用户关键字和变量只能在创建它们的文件中使用,但资源文件提供了共享它们的机制。创建资源文件的高级语法与创建套件文件时完全相同,支持的文件格式也相同。主要区别在于资源文件不能有测试。

Variable files provide a powerful mechanism for creating and sharing variables. For example, they allow values other than strings and enable creating variables dynamically. Their flexibility comes from the fact that they are created using Python or YAML, which also makes them somewhat more complicated than Variable sections.
变量文件为创建和共享变量提供了强大的机制。例如,它们允许字符串以外的值并支持动态创建变量。它们的灵活性来自于它们是使用Python或YAML创建的,这也使得它们比Variable节更复杂。

2.8.1   Resource files 2.8.1资源文件

Resource files are typically created using the plain text format, but also reStructuredText format and JSON format are supported.
资源文件通常使用纯文本格式创建,但也支持reStructuredText格式JSON格式

Taking resource files into use
使用资源文件

Resource files are imported using the Resource setting in the Settings section so that the path to the resource file is given as an argument to the setting. The recommended extension for resource files is .resource. For backwards compatibility reasons also .robot, .txt and .tsv work, but using .resource may be mandated in the future.
使用“设置”部分中的“资源”设置导入资源文件,以便将资源文件的路径作为设置的参数提供。资源文件的推荐扩展名是.resource。出于向后兼容性的原因,.robot.txt.tsv也可以使用,但将来可能会强制使用.resource

If the resource file path is absolute, it is used directly. Otherwise, the resource file is first searched relatively to the directory where the importing file is located. If the file is not found there, it is then searched from the directories in Python's module search path. Searching resource files from the module search path makes it possible to bundle them into Python packages as package data and importing them like package/example.resource.
如果资源文件路径是绝对路径,则直接使用它。否则,先相对于导入文件所在目录查找资源文件。如果没有找到该文件,则从Python的模块搜索路径中的目录中搜索该文件。从模块搜索路径中搜索资源文件可以将它们作为包数据捆绑到Python包中,并像package/example.resource一样导入它们。

The resource file path can contain variables, and it is recommended to use them to make paths system-independent (for example, ${RESOURCES}/login.resource or just ${RESOURCE_PATH}). Additionally, forward slashes (/) in the path are automatically changed to backslashes (\) on Windows.
资源文件路径可以包含变量,建议使用它们使路径与系统无关(例如,${RESOURCES}/login.resource或仅${RESOURCE_PATH})。此外,在Windows上,路径中的正斜杠(/)会自动更改为反斜杠(\)。

*** Settings ***
Resource    example.resource
Resource    ../resources/login.resource
Resource    package/example.resource
Resource    ${RESOURCES}/common.resource

The user keywords and variables defined in a resource file are available in the file that takes that resource file into use. Similarly available are also all keywords and variables from the libraries, resource files and variable files imported by the said resource file.
在资源文件中定义的用户关键字和变量在使用该资源文件的文件中可用。同样可用的还有来自库、资源文件和由所述资源文件导入的变量文件的所有关键字和变量。

Note 注意

The .resource extension is new in Robot Framework 3.1.
.resource扩展名是Robot Framework 3.1中的新功能。

Resource file structure 资源文件结构

The higher-level structure of resource files is the same as that of suite files otherwise, but they cannot contain tests or tasks. Additionally, the Setting section in resource files can contain only imports (Library, Resource, Variables), Documentation and Keyword Tags. The Variable section and Keyword section are used exactly the same way as in suite files.
资源文件的高级结构与套件文件的结构相同,但它们不能包含测试或任务。此外,资源文件中的设置部分只能包含导入(资源变量)、文档关键字标签。变量部分和关键字部分的使用方式与套件文件中的完全相同。

If several resource files have a user keyword with the same name, they must be used so that the keyword name is prefixed with the resource file name without the extension (for example, myresources.Some Keyword and common.Some Keyword). Moreover, if several resource files contain the same variable, the one that is imported first is taken into use.
如果多个资源文件的用户关键字具有相同的名称,则必须使用它们,以便关键字名称以不带扩展名的资源文件名作为前缀(例如,myresources.Some Keywordcommon.Some Keyword)。此外,如果多个资源文件包含相同的变量,则首先导入的变量将被使用。

Documenting resource files
记录资源文件

Keywords created in a resource file can be documented using [Documentation] setting. The resource file itself can have Documentation in the Setting section similarly as suites.
在资源文件中创建的关键字可以使用[Documentation]设置进行记录。资源文件本身可以在设置部分中包含文档,类似于套件

Libdoc and various editors use these documentations, and they are naturally available for anyone opening resource files. The first logical line of the documentation of a keyword, until the first empty line, is logged when the keyword is run, but otherwise resource file documentation is ignored during the test execution.
Libdoc和各种编辑器使用这些文档,它们自然可供任何打开资源文件的人使用。关键字文档的第一个逻辑行(直到第一个空行)在关键字运行时被记录,但在测试执行期间忽略其他资源文件文档。

Example resource file 示例资源文件

*** Settings ***
Documentation     An example resource file
Library           SeleniumLibrary
Resource          ${RESOURCES}/common.resource

*** Variables ***
${HOST}           localhost:7272
${LOGIN URL}      http://${HOST}/
${WELCOME URL}    http://${HOST}/welcome.html
${BROWSER}        Firefox

*** Keywords ***
Open Login Page
    [Documentation]    Opens browser to login page
    Open Browser    ${LOGIN URL}    ${BROWSER}
    Title Should Be    Login Page

Input Name
    [Arguments]    ${name}
    Input Text    username_field    ${name}

Input Password
    [Arguments]    ${password}
    Input Text    password_field    ${password}

Resource files using reStructured text format
使用reStructured文本格式的资源文件

The reStructuredText format that can be used with suite files works also with resource files. Such resource files can use either .rst or .rest extension and they are otherwise imported exactly as normal resource files:
可用于套件文件reStructuredText格式也可用于资源文件。这些资源文件可以使用.rst.rest扩展名,否则它们将完全作为普通资源文件导入:

*** Settings ***
Resource         example.rst

When parsing resource files using the reStructuredText format, Robot Framework ignores all data outside code blocks containing Robot Framework data exactly the same way as when parsing reStructuredText suite files. For example, the following resource file imports OperatingSystem library, defines ${MESSAGE} variable and creates My Keyword keyword:
当使用reStructuredText格式解析资源文件时,Robot Framework将忽略包含Robot Framework数据的代码块之外的所有数据,其方式与解析reStructuredText套件文件时完全相同。例如,以下资源文件导入OperatingSystem库,定义${MESSAGE}变量并创建My Keyword关键字:

Resource file using reStructuredText
------------------------------------

This text is outside code blocks and thus ignored.

.. code:: robotframework

   *** Settings ***
   Library          OperatingSystem

   *** Variables ***
   ${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} |

Resource files using JSON format
使用JSON格式的资源文件

Resource files can be created using JSON the same way as suite files. Such JSON resource files must use either the standard .json extension or the custom .rsrc extension. They are otherwise imported exactly as normal resource files:
资源文件可以像套件文件一样使用JSON创建。此类JSON资源文件必须使用标准.json扩展名或自定义.rsrc扩展名。否则,它们将完全作为普通资源文件导入:

*** Settings ***
Resource         example.rsrc

Resource files can be converted to JSON using ResourceFile.to_json and recreated using ResourceFile.from_json:
可以使用ResourceFile.to_json将资源文件转换为JSON,并使用ResourceFile.from_json重新创建:

from robot.running import ResourceFile


# Create resource file based on data on the file system.
resource = ResourceFile.from_file_system('example.resource')

# Save JSON data to a file.
resource.to_json('example.rsrc')

# Recreate resource from JSON data.
resource = ResourceFile.from_json('example.rsrc')

2.8.2   Variable files 2.8.2变量文件

Variable files contain variables that can be used in the test data. Variables can also be created using Variable sections or set from the command line, but variable files allow creating them dynamically and also make it easy to create other variable values than strings.
变量文件包含可在测试数据中使用的变量。变量也可以使用Variable部分创建或从命令行设置,但变量文件允许动态创建它们,并且还可以轻松创建字符串以外的其他变量值。

Variable files are typically implemented as modules and there are two different approaches for creating variables:
变量文件通常作为模块实现,有两种不同的方法来创建变量:

Getting variables directly from a module
直接从模块中获取变量
Variables are specified as module attributes. In simple cases, the syntax is so simple that no real programming is needed. For example, MY_VAR = 'my value' creates a variable ${MY_VAR} with the specified text as its value. One limitation of this approach is that it does not allow using arguments.
变量被指定为模块属性。在简单的情况下,语法非常简单,不需要真实的编程。例如,MY_VAR = 'my value'将创建一个变量${MY_VAR},并将指定的文本作为其值。这种方法的一个限制是它不允许使用参数。
Getting variables from a special function
从特殊函数中获取变量
Variable files can have a special get_variables (or getVariables) method that returns variables as a mapping. Because the method can take arguments this approach is very flexible.
变量文件可以有一个特殊的get_variables(或getVariables)方法,该方法将变量作为映射返回。因为该方法可以接受参数,所以这种方法非常灵活。

Alternatively variable files can be implemented as classes that the framework will instantiate. Also in this case it is possible to create variables as attributes or get them dynamically from the get_variables method. Variable files can also be created as YAML and JSON.
或者,变量文件可以实现为框架将实例化的。同样在这种情况下,可以将变量创建为属性或从get_variables方法动态获取它们。变量文件也可以创建为YAMLJSON

Taking variable files into use
使用变量文件

Setting section 设定部

All test data files can import variable files using the Variables setting in the Setting section. Variable files are typically imported using a path to the file same way as resource files are imported using the Resource setting. Similarly to resource files, the path to the imported variable file is considered relative to the directory where the importing file is, and if not found, it is searched from directories in the module search path. The path can also contain variables, and slashes are converted to backslashes on Windows.
所有测试数据文件都可以使用设置部分中的变量设置导入变量文件。变量文件通常使用文件的路径导入,方式与使用资源设置导入资源文件的方式相同。与资源文件类似,导入的变量文件的路径被认为是相对于导入文件所在的目录,如果找不到,则从模块搜索路径中的目录中搜索。路径还可以包含变量,在Windows上,斜杠被转换为反斜杠。

Examples: 示例如下:

*** Settings ***
Variables    myvariables.py
Variables    ../data/variables.py
Variables    ${RESOURCES}/common.yaml

Starting from Robot Framework 5.0, variable files implemented using Python can also be imported using the module name similarly as libraries. When using this approach, the module needs to be in the module search path.
从Robot Framework 5.0开始,使用Python实现的变量文件也可以使用类似于库的模块名称导入。使用此方法时,模块需要位于模块搜索路径中。

Examples: 示例如下:

*** Settings ***
Variables    myvariables
Variables    rootmodule.Variables

If a variable file accepts arguments, they are specified after the path or name of the variable file to import:
如果变量文件接受参数,则在要导入的变量文件的路径或名称之后指定参数:

*** Settings ***
Variables    arguments.py    arg1    ${ARG2}
Variables    arguments    argument

All variables from a variable file are available in the test data file that imports it. If several variable files are imported and they contain a variable with the same name, the one in the earliest imported file is taken into use. Additionally, variables created in Variable sections and set from the command line override variables from variable files.
变量文件中的所有变量都可以在导入该文件的测试数据文件中使用。如果导入了多个变量文件,并且它们包含具有相同名称的变量,则使用最早导入的文件中的变量。此外,在Variable部分中创建的变量和从命令行设置的变量会覆盖变量文件中的变量。

Command line 命令行

Another way to take variable files into use is using the command line option --variablefile. Variable files are referenced using a path or module name similarly as when importing them using the Variables setting. Possible arguments are joined to the path with a colon (:):
使用变量文件的另一种方法是使用命令行选项--variablefile。变量文件使用路径或模块名引用,与使用Variables设置导入它们时类似。可能的参数用冒号()连接到路径:

--variablefile myvariables.py
--variablefile path/variables.py
--variablefile /absolute/path/common.py
--variablefile variablemodule
--variablefile arguments.py:arg1:arg2
--variablefile rootmodule.Variables:arg1:arg2

Variable files taken into use from the command line are also searched from the module search path similarly as variable files imported in the Setting section. Relative paths are considered relative to the directory where execution is started from.
从命令行中使用的变量文件也会从模块搜索路径中搜索,与在设置部分中导入的变量文件类似。相对路径被认为是相对于执行开始的目录。

If a variable file is given as an absolute Windows path, the colon after the drive letter is not considered a separator:
如果变量文件作为绝对Windows路径给出,则驱动器号后的冒号不被视为分隔符:

--variablefile C:\path\variables.py

It is also possible to use a semicolon (;) as an argument separator. This is useful if variable file arguments themselves contain colons, but requires surrounding the whole value with quotes on UNIX-like operating systems:
也可以使用一个分隔符(;)作为参数分隔符。如果变量文件参数本身包含冒号,这很有用,但在类UNIX操作系统上需要用引号将整个值括起来:

--variablefile C:\path\variables.py;D:\data.xls
--variablefile "myvariables.py;argument:with:colons"

Variables in variable files taken use on the command line are globally available in all test data files, similarly as individual variables set with the --variable option. If both --variablefile and --variable options are used and there are variables with same names, those that are set individually with --variable option take precedence.
在命令行上使用的变量文件中的变量在所有测试数据文件中全局可用,类似于使用--variable选项设置的单个变量。如果同时使用--variablefile--variable选项,并且存在同名的变量,则使用--variable选项单独设置的变量优先。

Getting variables directly from a module
直接从模块中获取变量

Basic syntax 基本语法

When variable files are taken into use, they are imported as Python modules and all their module level attributes that do not start with an underscore (_) are, by default, considered to be variables. Because variable names are case-insensitive, both lower- and upper-case names are possible, but in general, capital letters are recommended for global variables and attributes.
当变量文件被使用时,它们被导入为Python模块,并且它们的所有模块级属性(不以下划线(_)开头)默认被认为是变量。因为变量名不区分大小写,所以小写和大写名称都是可能的,但通常建议全局变量和属性使用大写字母。

VARIABLE = "An example string"
ANOTHER_VARIABLE = "This is pretty easy!"
INTEGER = 42
STRINGS = ["one", "two", "kolme", "four"]
NUMBERS = [1, INTEGER, 3.14]
MAPPING = {"one": 1, "two": 2, "three": 3}

In the example above, variables ${VARIABLE}, ${ANOTHER VARIABLE}, and so on, are created. The first two variables are strings, the third one is an integer, then there are two lists, and the final value is a dictionary. All these variables can be used as a scalar variable, lists and the dictionary also a list variable like @{STRINGS} (in the dictionary's case that variable would only contain keys), and the dictionary also as a dictionary variable like &{MAPPING}.
在上面的示例中,创建了变量${VARIABLE}${ANOTHER VARIABLE}等。前两个变量是字符串,第三个是整数,然后有两个列表,最后一个值是字典。所有这些变量都可以用作标量变量,列表和字典也可以用作列表变量,如@{STRINGS}(在字典的情况下,该变量只包含键),字典也可以用作字典变量,如&{MAPPING}

To make creating a list variable or a dictionary variable more explicit, it is possible to prefix the variable name with LIST__ or DICT__, respectively:
为了更明确地创建列表变量或字典变量,可以分别在变量名前面加上LIST__DICT__

from collections import OrderedDict

LIST__ANIMALS = ["cat", "dog"]
DICT__FINNISH = OrderedDict([("cat", "kissa"), ("dog", "koira")])

These prefixes will not be part of the final variable name, but they cause Robot Framework to validate that the value actually is list-like or dictionary-like. With dictionaries the actual stored value is also turned into a special dictionary that is used also when creating dictionary variables in the Variable section. Values of these dictionaries are accessible as attributes like ${FINNISH.cat}. These dictionaries are also ordered, but preserving the source order requires also the original dictionary to be ordered.
这些前缀不会成为最终变量名的一部分,但它们会使Robot Framework验证该值实际上是列表式还是字典式。使用字典,实际存储的值也被转换成一个特殊的字典,当在Variable部分创建字典变量时也会使用这个字典。这些字典的值可以作为属性访问,如${FINNISH.cat}。这些字典也是有序的,但是保持源顺序也需要对原始字典进行排序。

The variables in both the examples above could be created also using the Variable section below.
上面两个例子中的变量也可以使用下面的变量部分创建。

*** Variables ***
${VARIABLE}            An example string
${ANOTHER VARIABLE}    This is pretty easy!
${INTEGER}             ${42}
@{STRINGS}             one          two           kolme         four
@{NUMBERS}             ${1}         ${INTEGER}    ${3.14}
&{MAPPING}             one=${1}     two=${2}      three=${3}
@{ANIMALS}             cat          dog
&{FINNISH}             cat=kissa    dog=koira

Note 注意

Variables are not replaced in strings got from variable files. For example, VAR = "an ${example}" would create variable ${VAR} with a literal string value an ${example} regardless would variable ${example} exist or not.
在从变量文件获取的字符串中,变量不会被替换。例如,VAR =“an ${example}”将创建具有文本字符串值an ${example}的变量${VAR},而不管变量${example}是否存在。

Using objects as values 使用对象作为值

Variables in variable files are not limited to having only strings or other base types as values like Variable sections. Instead, their variables can contain any objects. In the example below, the variable ${MAPPING} contains a Python dictionary and also has two variables created from a custom object implemented in the same file.
变量文件中的变量不限于只有字符串或其他基本类型作为值,如Variable部分。相反,它们的变量可以包含任何对象。在下面的示例中,变量${MAPPING}包含一个Python字典,还包含两个从同一文件中实现的自定义对象创建的变量。

MAPPING = {'one': 1, 'two': 2}

class MyObject:
    def __init__(self, name):
        self.name = name

OBJ1 = MyObject('John')
OBJ2 = MyObject('Jane')
Creating variables dynamically
动态创建变量

Because variable files are created using a real programming language, they can have dynamic logic for setting variables.
因为变量文件是使用真实的编程语言创建的,所以它们可以具有用于设置变量的动态逻辑。

import os
import random
import time

USER = os.getlogin()                # current login name
RANDOM_INT = random.randint(0, 10)  # random integer in range [0,10]
CURRENT_TIME = time.asctime()       # timestamp like 'Thu Apr  6 12:45:21 2006'
if time.localtime()[3] > 12:
    AFTERNOON = True
else:
    AFTERNOON = False

The example above uses standard Python libraries to set different variables, but you can use your own code to construct the values. The example below illustrates the concept, but similarly, your code could read the data from a database, from an external file or even ask it from the user.
上面的示例使用标准Python库来设置不同的变量,但您可以使用自己的代码来构造值。下面的例子说明了这个概念,但类似地,你的代码可以从数据库、外部文件甚至从用户那里读取数据。

import math

def get_area(diameter):
    radius = diameter / 2
    area = math.pi * radius * radius
    return area

AREA1 = get_area(1)
AREA2 = get_area(2)
Selecting which variables to include
选择要包含的变量

When Robot Framework processes variable files, all their attributes that do not start with an underscore are expected to be variables. This means that even functions or classes created in the variable file or imported from elsewhere are considered variables. For example, the last example would contain the variables ${math} and ${get_area} in addition to ${AREA1} and ${AREA2}.
当Robot Framework处理变量文件时,所有不以下划线开头的属性都应该是变量。这意味着即使是在变量文件中创建或从其他地方导入的函数或类也被认为是变量。例如,最后一个示例将包含变量${math}${get_area}以及${AREA 1}${AREA 2}

Normally the extra variables do not cause problems, but they could override some other variables and cause hard-to-debug errors. One possibility to ignore other attributes is prefixing them with an underscore:
通常,额外的变量不会导致问题,但它们可能会覆盖其他一些变量,并导致难以调试的错误。忽略其他属性的一种可能性是使用下划线作为前缀:

import math as _math

def _get_area(diameter):
    radius = diameter / 2.0
    area = _math.pi * radius * radius
    return area

AREA1 = _get_area(1)
AREA2 = _get_area(2)

If there is a large number of other attributes, instead of prefixing them all, it is often easier to use a special attribute __all__ and give it a list of attribute names to be processed as variables.
如果有大量的其他属性,而不是把它们都加前缀,通常更容易使用一个特殊的属性__all__,并给它一个属性名称列表作为变量处理。

import math

__all__ = ['AREA1', 'AREA2']

def get_area(diameter):
    radius = diameter / 2.0
    area = math.pi * radius * radius
    return area

AREA1 = get_area(1)
AREA2 = get_area(2)

Note 注意

The __all__ attribute is also, and originally, used by Python to decide which attributes to import when using the syntax from modulename import *.
__all__属性最初也被Python用来决定在使用modulatable import *语法时导入哪些属性。

The third option to select what variables are actually created is using a special get_variables function discussed below.
选择实际创建哪些变量的第三个选项是使用下面讨论的特殊get_variables函数。

Getting variables from a special function
从特殊函数中获取变量

An alternative approach for getting variables is having a special get_variables function (also camelCase syntax getVariables is possible) in a variable file. If such a function exists, Robot Framework calls it and expects to receive variables as a Python dictionary with variable names as keys and variable values as values. Created variables can be used as scalars, lists, and dictionaries exactly like when getting variables directly from a module, and it is possible to use LIST__ and DICT__ prefixes to make creating list and dictionary variables more explicit. The example below is functionally identical to the first example related to getting variables directly from a module.
获取变量的另一种方法是在变量文件中使用特殊的get_variables函数(也可以使用camelCase语法getVariables)。如果存在这样的函数,Robot Framework会调用它,并期望以Python字典的形式接收变量,变量名作为键,变量值作为值。创建的变量可以用作标量,列表和字典,就像直接从模块中获取变量一样,并且可以使用LIST__DICT__前缀来使创建列表和字典变量更显式。下面的例子在功能上与第一个直接从模块获取变量的例子相同。

def get_variables():
    variables = {"VARIABLE ": "An example string",
                 "ANOTHER VARIABLE": "This is pretty easy!",
                 "INTEGER": 42,
                 "STRINGS": ["one", "two", "kolme", "four"],
                 "NUMBERS": [1, 42, 3.14],
                 "MAPPING": {"one": 1, "two": 2, "three": 3}}
    return variables

get_variables can also take arguments, which facilitates changing what variables actually are created. Arguments to the function are set just as any other arguments for a Python function. When taking variable files into use, arguments are specified after the path to the variable file, and in the command line they are separated from the path with a colon or a semicolon.
get_variables也可以接受参数,这有助于更改实际创建的变量。函数的参数设置方式与Python函数的其他参数设置方式相同。当使用变量文件时,在变量文件的路径之后指定参数,在命令行中,用冒号或分号将参数与路径分隔开。

The dummy example below shows how to use arguments with variable files. In a more realistic example, the argument could be a path to an external text file or database where to read variables from.
下面的虚拟示例显示了如何在变量文件中使用参数。在一个更现实的例子中,参数可以是一个外部文本文件或数据库的路径,从中读取变量。

variables1 = {'scalar': 'Scalar variable',
              'LIST__list': ['List','variable']}
variables2 = {'scalar' : 'Some other value',
              'LIST__list': ['Some','other','value'],
              'extra': 'variables1 does not have this at all'}

def get_variables(arg):
    if arg == 'one':
        return variables1
    else:
        return variables2

Starting from Robot Framework 7.0, arguments to variable files support automatic argument conversion as well as named argument syntax. For example, a variable file with get_variables(first: int = 0, second: str = '') could be imported like this:
从Robot Framework 7.0开始,变量文件的参数支持自动参数转换以及命名参数语法。例如,一个变量文件get_variables(first:int = 0,second:str =“”)可以这样导入:

*** Settings ***
Variables    example.py    42              # Converted to integer.
Variables    example.py    second=value    # Named argument syntax.

Implementing variable file as a class
将变量文件实现为类

It is possible to implement variables files also as a class.
也可以将变量文件实现为类。

Implementation 执行

Because variable files are always imported using a file system path, the class must have the same name as the module it is located in.
因为变量文件总是使用文件系统路径导入的,所以类必须与它所在的模块同名。

The framework will create an instance of the class using no arguments and variables will be gotten from the instance. Similarly as with modules, variables can be defined as attributes directly in the instance or gotten from a special get_variables method.
框架将创建一个不使用参数的类的实例,变量将从实例中获取。与模块类似,变量可以直接在实例中定义为属性,也可以从特殊的get_variables方法中获取。

When variables are defined directly in an instance, all attributes containing callable values are ignored to avoid creating variables from possible methods the instance has. If you would actually need callable variables, you need to use other approaches to create variable files.
当变量直接在实例中定义时,所有包含可调用值的属性都将被忽略,以避免从实例具有的可能方法创建变量。如果你真的需要可调用变量,你需要使用其他方法来创建变量文件。

Examples 示例

The first examples create variables from attributes. It creates variables ${VARIABLE} and @{LIST} from class attributes and ${ANOTHER VARIABLE} from an instance attribute.
第一个示例从属性创建变量。它从类属性创建变量${VARIABLE}@{LIST},从实例属性创建变量${ANOTHER VARIABLE}

class StaticExample:
    variable = 'value'
    LIST__list = [1, 2, 3]
    _not_variable = 'starts with an underscore'

    def __init__(self):
        self.another_variable = 'another value'

The second examples utilizes dynamic approach for getting variables. It creates only one variable ${DYNAMIC VARIABLE}.
第二个例子使用动态方法来获取变量。它只创建一个变量${DYNAMIC VARIABLE}

class DynamicExample:

    def get_variables(self, *args):
        return {'dynamic variable': ' '.join(args)}

Variable file as YAML 变量文件作为YAML

Variable files can also be implemented as YAML files. YAML is a data serialization language with a simple and human-friendly syntax that is nevertheless easy for machines to parse. The following example demonstrates a simple YAML file:
变量文件也可以实现为YAML文件。YAML是一种数据序列化语言,具有简单且人性化的语法,但易于机器解析。下面的示例演示了一个简单的YAML文件:

string:   Hello, world!
integer:  42
list:
  - one
  - two
dict:
  one: yksi
  two: kaksi
  with spaces: kolme

YAML variable files can be used exactly like normal variable files from the command line using --variablefile option, in the Settings section using Variables setting, and dynamically using the Import Variables keyword. They are automatically recognized by their extension that must be either .yaml or .yml. If the above YAML file is imported, it will create exactly the same variables as this Variable section:
YAML变量文件可以完全像普通变量文件一样使用,从命令行使用--variablefile选项,在设置部分使用Variables设置,并动态使用Import Variables关键字。它们通过扩展名自动识别,扩展名必须是.yaml.yml。如果导入上述YAML文件,它将创建与此Variable部分完全相同的变量:

*** Variables ***
${STRING}     Hello, world!
${INTEGER}    ${42}
@{LIST}       one         two
&{DICT}       one=yksi    two=kaksi    with spaces=kolme

YAML files used as variable files must always be mappings on the top level. As the above example demonstrates, keys and values in the mapping become variable names and values, respectively. Variable values can be any data types supported by YAML syntax. If names or values contain non-ASCII characters, YAML variables files must be UTF-8 encoded.
用作变量文件的YAML文件必须始终是顶层的映射。如上面的示例所示,映射中的键和值分别成为变量名和值。变量值可以是YAML语法支持的任何数据类型。如果名称或值包含非ASCII字符,则YAML变量文件必须是UTF-8编码的。

Mappings used as values are automatically converted to special dictionaries that are used also when creating dictionary variables in the Variable section. Most importantly, values of these dictionaries are accessible as attributes like ${DICT.one}, assuming their names are valid as Python attribute names. If the name contains spaces or is otherwise not a valid attribute name, it is always possible to access dictionary values using syntax like ${DICT}[with spaces] syntax.
用作值的映射会自动转换为特殊字典,在Variable部分中创建字典变量时也会使用这些字典。最重要的是,这些字典的值可以作为属性访问,如${DICT.one},假设它们的名称作为Python属性名称有效。如果名称包含空格或不是有效的属性名称,则始终可以使用${DICT}[with spaces]语法访问字典值。

Note 注意

Using YAML files with Robot Framework requires PyYAML module to be installed. You can typically install it with pip like pip install pyyaml.
在Robot Framework中使用YAML文件需要安装PyYAML模块。您通常可以使用pip安装它,例如pip install pyyaml

Variable file as JSON 变量文件为JSON

Variable files can also be implemented as JSON files. Similarly as YAML discussed in the previous section, JSON is a data serialization format targeted both for humans and machines. It is based on JavaScript syntax and it is not as human-friendly as YAML, but it still relatively easy to understand and modify. The following example contains exactly the same data as the earlier YAML example:
变量文件也可以实现为JSON文件。与上一节中讨论的YAML类似,JSON是一种针对人类和机器的数据序列化格式。它基于JavaScript语法,不像YAML那样人性化,但它仍然相对容易理解和修改。下面的示例包含与前面的YAML示例完全相同的数据:

{
    "string": "Hello, world!",
    "integer": 42,
    "list": [
        "one",
        "two"
    ],
    "dict": {
        "one": "yksi",
        "two": "kaksi",
        "with spaces": "kolme"
    }
}

JSON variable files are automatically recognized by their .json extension and they can be used exactly like YAML variable files. They also have exactly same requirements for structure, encoding, and so on. Unlike YAML, Python supports JSON out-of-the-box so no extra modules need to be installed.
JSON变量文件通过其.json扩展名自动识别,它们可以像YAML变量文件一样使用。它们对结构、编码等也有完全相同的要求。与YAML不同,Python支持JSON开箱即用,因此不需要安装额外的模块。

Note 注意

Support for JSON variable files is new in Robot Framework 6.1.
对JSON变量文件的支持是Robot Framework 6.1中的新功能。

2.9   Control structures 2.9控制结构

This section describes various structures that can be used to control the test execution flow. These structures are familiar from most programming languages and they allow conditional execution, repeatedly executing a block of keywords and fine-grained error handling. For readability reasons these structures should be used judiciously, and more complex use cases should be preferably implemented in test libraries.
本节描述可用于控制测试执行流的各种结构。这些结构在大多数编程语言中都很常见,它们允许条件执行,重复执行关键字块和细粒度的错误处理。出于可读性的考虑,应该明智地使用这些结构,更复杂的用例应该优先在测试库中实现。

2.9.1   FOR loops
2.9.1FOR循环

Repeating same actions several times is quite a common need in test automation. With Robot Framework, test libraries can have any kind of loop constructs, and most of the time loops should be implemented in them. Robot Framework also has its own FOR loop syntax, which is useful, for example, when there is a need to repeat keywords from different libraries.
在测试自动化中,多次重复相同的操作是一个相当普遍的需求。使用Robot Framework,测试库可以有任何类型的循环结构,并且大多数时间循环都应该在其中实现。Robot Framework也有自己的FOR循环语法,例如,当需要重复来自不同库的关键字时,这很有用。

FOR loops can be used with both test cases and user keywords. Except for really simple cases, user keywords are better, because they hide the complexity introduced by FOR loops. The basic FOR loop syntax, FOR item IN sequence, is derived from Python, but similar syntax is supported also by various other programming languages.
FOR循环可以与测试用例和用户关键字一起使用。除了非常简单的情况,用户关键字更好,因为它们隐藏了FOR循环引入的复杂性。基本FOR循环语法(FOR项IN序列)源自Python,但各种其他编程语言也支持类似的语法。

Simple FOR loop
简单的FOR循环

In a normal FOR loop, one variable is assigned based on a list of values, one value per iteration. The syntax starts with FOR (case-sensitive) as a marker, then the loop variable, then a mandatory IN (case-sensitive) as a separator, and finally the values to iterate. These values can contain variables, including list variables.
在正常的FOR循环中,根据值列表分配一个变量,每次迭代分配一个值。该语法以FOR(区分大小写)作为标记开始,然后是循环变量,然后是强制性的IN(区分大小写)作为分隔符,最后是要删除的值。这些值可以包含变量,包括列表变量

The keywords used in the FOR loop are on the following rows and the loop ends with END (case-sensitive) on its own row. Keywords inside the loop do not need to be indented, but that is highly recommended to make the syntax easier to read.
FOR循环中使用的关键字位于后面的行中,循环以自己行中的END(区分大小写)结束。循环中的关键字不需要缩进,但强烈建议这样做,以使语法更容易阅读。

*** Test Cases ***
Example
    FOR    ${animal}    IN    cat    dog
        Log    ${animal}
        Log    2nd keyword
    END
    Log    Outside loop

Second Example
    FOR    ${var}    IN    one    two    ${3}    four    ${five}
    ...    kuusi    7    eight    nine    ${last}
        Log    ${var}
    END

The FOR loop in Example above is executed twice, so that first the loop variable ${animal} has the value cat and then dog. The loop consists of two Log keywords. In the second example, loop values are split into two rows and the loop is run altogether ten times.
上面的例子中的FOR循环执行了两次,所以首先循环变量${animal}的值是cat,然后是dog。该循环由两个Log关键字组成。在第二个示例中,循环值被拆分为两行,循环总共运行十次。

It is often convenient to use FOR loops with list variables. This is illustrated by the example below, where @{ELEMENTS} contains an arbitrarily long list of elements and keyword Start Element is used with all of them one by one.
对于列表变量使用FOR循环通常很方便。下面的例子说明了这一点,其中@{ELEMENTS}包含一个任意长的元素列表,关键字Start Element与所有元素逐一使用。

*** Test Cases ***
Example
    FOR    ${element}    IN    @{ELEMENTS}
        Start Element    ${element}
    END

Old FOR loop syntax
的FOR循环语法

Prior to Robot Framework 3.1, the FOR loop syntax was different than nowadays. The marker to start the loop was :FOR instead of FOR and loop contents needed to be explicitly marked with a backslash instead of using the END marker to end the loop. The first example above would look like this using the old syntax:
在Robot Framework 3.1之前,FOR循环语法与现在不同。开始循环的标记是:FOR而不是FOR,循环内容需要用反斜杠显式标记,而不是使用END标记来结束循环。上面的第一个例子看起来像这样使用旧的语法:

*** Test Cases ***
Example
    :FOR    ${animal}    IN    cat    dog
    \    Log    ${animal}
    \    Log    2nd keyword
    Log    Outside loop

The old syntax was deprecated in Robot Framework 3.2 and the support for it was removed altogether in Robot Framework 4.0.
旧的语法在Robot Framework 3.2中被弃用,在Robot Framework 4.0中完全删除了对它的支持。

Nesting FOR loops
嵌套FOR循环

Starting from Robot Framework 4.0, it is possible to use nested FOR loops simply by adding a loop inside another loop:
从Robot Framework 4.0开始,可以通过在另一个循环中添加一个循环来使用嵌套的FOR循环:

*** Keywords ***
Handle Table
    [Arguments]    @{table}
    FOR    ${row}    IN    @{table}
        FOR    ${cell}    IN    @{row}
            Handle Cell    ${cell}
        END
    END

There can be multiple nesting levels and loops can also be combined with other control structures:
可以有多个嵌套级别,循环也可以与其他控制结构组合:

*** Test Cases ***
Multiple nesting levels
    FOR    ${root}    IN    r1    r2
        FOR    ${child}    IN    c1   c2    c3
            FOR    ${grandchild}    IN    g1    g2
                Log Many    ${root}    ${child}    ${grandchild}
            END
        END
        FOR    ${sibling}    IN    s1    s2    s3
            IF    '${sibling}' != 's2'
                Log Many    ${root}    ${sibling}
            END
        END
    END

Using several loop variables
使用多个循环变量

It is possible to iterate over multiple values in one iteration by using multiple loop variables between the FOR and IN markers. There can be any number of loop variables, but the number of values must be evenly dividable by the number of variables. Each iteration consumes as many values as there are variables.
通过在FORIN标记之间使用多个循环变量,可以在一次迭代中遍历多个值。可以有任意数量的循环变量,但值的数量必须能被变量的数量整除。每次迭代消耗的值与变量一样多。

If there are lot of values to iterate, it is often convenient to organize them below the loop variables, as in the first loop of the example below:
如果有很多值需要处理,通常可以方便地将它们组织在循环变量下面,如下面示例的第一个循环:

*** Test Cases ***
Multiple loop variables
    FOR    ${index}    ${english}    ${finnish}    IN
    ...    1           cat           kissa
    ...    2           dog           koira
    ...    3           horse         hevonen
        Add Translation    ${english}    ${finnish}    ${index}
    END
    FOR    ${name}    ${id}    IN    @{EMPLOYERS}
        Create    ${name}    ${id}
    END

FOR-IN-RANGE loop
FOR-IN-RANGE循环

All FOR loops in the previous section iterated over a sequence. That is the most common use case, but sometimes it is convenient to have a loop that is executed a certain number of times. For this purpose Robot Framework has a special FOR index IN RANGE limit loop syntax that is derived from the similar Python idiom using the built-in range() function.
上一节中的所有FOR循环都在一个序列上迭代。这是最常见的用例,但有时候执行一定次数的循环会很方便。为此,Robot Framework有一个特殊的FOR索引IN RANGE限制循环语法,该语法是使用内置的range()函数从类似的Python习惯用法中派生出来的。

Similarly as other FOR loops, the FOR-IN-RANGE loop starts with FOR that is followed by a loop variable. In this format there can be only one loop variable and it contains the current loop index. After the variable there must be IN RANGE marker (case-sensitive) that is followed by loop limits.
与其他FOR循环类似,FOR-IN-RANGE循环以FOR开始,后跟一个循环变量。在这种格式中,只能有一个循环变量,它包含当前循环索引。在变量后必须有IN RANGE标记(区分大小写),后面跟着循环限制。

In the simplest case, only the upper limit of the loop is specified. In this case, loop indices start from zero and increase by one until, but excluding, the limit. It is also possible to give both the start and end limits. Then indices start from the start limit, but increase similarly as in the simple case. Finally, it is possible to give also the step value that specifies the increment to use. If the step is negative, it is used as decrement.
在最简单的情况下,只指定循环的上限。在这种情况下,循环索引从零开始,递增1,直到极限,但不包括极限。也可以同时给出开始和结束限制。然后索引从开始限制开始,但与简单情况类似地增加。最后,还可以给出指定要使用的增量的步长值。如果步长为负,则用作递减。

It is possible to use simple arithmetic such as addition and subtraction with the range limits. This is especially useful when the limits are specified with variables. Start, end and step are typically given as integers, but using float values is possible as well.
可以使用简单的算术运算,例如与范围限制的加法和减法。这在使用变量指定限值时特别有用。开始、结束和步长通常以整数形式给出,但也可以使用浮点值。

*** Test Cases ***
Only upper limit
    [Documentation]    Loops over values from 0 to 9.
    FOR    ${index}    IN RANGE    10
        Log    ${index}
    END

Start and end
    [Documentation]    Loops over values from 1 to 10.
    FOR    ${index}    IN RANGE    1    11
        Log    ${index}
    END

Also step given
    [Documentation]    Loops over values 5, 15, and 25.
    FOR    ${index}    IN RANGE    5    26    10
        Log    ${index}
    END

Negative step
    [Documentation]    Loops over values 13, 3, and -7.
    FOR    ${index}    IN RANGE    13    -13    -10
        Log    ${index}
    END

Arithmetic
    [Documentation]    Arithmetic with variable.
    FOR    ${index}    IN RANGE    ${var} + 1
        Log    ${index}
    END

Float parameters
    [Documentation]    Loops over values 3.14, 4.34, and 5.54.
    FOR    ${index}    IN RANGE    3.14    6.09    1.2
        Log    ${index}
    END

FOR-IN-ENUMERATE loop
FOR-IN-ENUMERATE循环

Sometimes it is useful to loop over a list and also keep track of your location inside the list. Robot Framework has a special FOR index ... IN ENUMERATE ... syntax for this situation. This syntax is derived from the Python built-in enumerate() function.
有时候,在列表上循环并跟踪您在列表中的位置是很有用的。Robot Framework有一个特殊的FOR索引...在枚举. 这种情况下的语法。此语法源自Python内置的enumerate()函数

FOR-IN-ENUMERATE loops syntax is just like the regular FOR loop syntax, except that the separator between variables and values is IN ENUMERATE (case-sensitive). Typically they are used so that there is an additional index variable before any other loop-variables. By default the index has a value 0 on the first iteration, 1 on the second, and so on.
FOR-IN-ENUMERATE循环语法与常规FOR循环语法类似,不同之处在于变量和值之间的分隔符是IN ENUMERATE(区分大小写)。通常使用它们是为了在任何其他循环变量之前有一个额外的索引变量。默认情况下,索引在第一次迭代中的值为0,在第二次迭代中的值为1,依此类推。

For example, the following two test cases do the same thing:
例如,以下两个测试用例执行相同的操作:

*** Variables ***
@{LIST}         a    b    c

*** Test Cases ***
Manage index manually
    ${index} =    Set Variable    -1
    FOR    ${item}    IN    @{LIST}
        ${index} =    Evaluate    ${index} + 1
        My Keyword    ${index}    ${item}
    END

FOR-IN-ENUMERATE
    FOR    ${index}    ${item}    IN ENUMERATE    @{LIST}
        My Keyword    ${index}    ${item}
    END

Starting from Robot Framework 4.0, it is possible to specify a custom start index by using start=<index> syntax as the last item of the FOR ... IN ENUMERATE ... header:
从Robot Framework 4.0开始,可以使用start=<index>语法指定自定义起始索引作为FOR.的最后一项。在枚举. 标题:

*** Variables ***
@{LIST}         a    b    c
${START}        10

*** Test Cases ***
FOR-IN-ENUMERATE with start
    FOR    ${index}    ${item}    IN ENUMERATE    @{LIST}    start=1
        My Keyword    ${index}    ${item}
    END

Start as variable
    FOR    ${index}    ${item}    IN ENUMERATE    @{LIST}    start=${start}
        My Keyword    ${index}    ${item}
    END

The start=<index> syntax must be explicitly used in the FOR header and it cannot itself come from a variable. If the last actual item to enumerate would start with start=, it needs to be escaped like start\=.
必须在FOR标头中显式使用start=<index>语法,并且它本身不能来自变量。如果要枚举的最后一个实际项将以start=开始,则需要像start\=那样对其进行转义。

Just like with regular FOR loops, you can loop over multiple values per loop iteration as long as the number of values in your list is evenly divisible by the number of loop-variables (excluding the index variable):
就像常规的FOR循环一样,你可以在每次循环迭代中循环多个值,只要列表中的值的数量可以被循环变量的数量整除(不包括索引变量):

*** Test Cases ***
FOR-IN-ENUMERATE with two values per iteration
    FOR    ${index}    ${en}    ${fi}    IN ENUMERATE
    ...    cat      kissa
    ...    dog      koira
    ...    horse    hevonen
        Log    "${en}" in English is "${fi}" in Finnish (index: ${index})
    END

If you only use one loop variable with FOR-IN-ENUMERATE loops, that variable will become a Python tuple containing the index and the iterated value:
如果在FOR-IN-ENUMERATE循环中只使用一个循环变量,该变量将成为包含索引和迭代值的Python元组:

*** Test Cases ***
FOR-IN-ENUMERATE with one loop variable
    FOR    ${x}    IN ENUMERATE    @{LIST}
        Length Should Be    ${x}    2
        Log    Index is ${x}[0] and item is ${x}[1].
    END

Note 注意

FOR-IN-ENUMERATE loops with only one loop variable is a new feature in Robot Framework 3.2.
只有一个循环变量的FOR-IN-ENUMERATE循环是Robot Framework 3.2中的新功能。

FOR-IN-ZIP loop
FOR-IN-ZIP循环

Some tests build up several related lists, then loop over them together. Robot Framework has a shortcut for this case: FOR ... IN ZIP ..., which is derived from the Python built-in zip() function.
有些测试建立了几个相关的列表,然后一起循环遍历它们。Robot Framework在这种情况下有一个快捷方式:FOR... IN ZIP... ,它派生自Python内置的zip()函数

This may be easiest to show with an example:
这可能是最容易用一个例子来说明:

*** Variables ***
@{NUMBERS}       ${1}    ${2}    ${5}
@{NAMES}         one     two     five

*** Test Cases ***
Iterate over two lists manually
    ${length}=    Get Length    ${NUMBERS}
    FOR    ${index}    IN RANGE    ${length}
        Log Many    ${NUMBERS}[${index}]    ${NAMES}[${index}]
    END

FOR-IN-ZIP
    FOR    ${number}    ${name}    IN ZIP    ${NUMBERS}    ${NAMES}
        Log Many    ${number}    ${name}
    END

As the example above illustrates, FOR-IN-ZIP loops require their own custom separator IN ZIP (case-sensitive) between loop variables and values. Values used with FOR-IN-ZIP loops must be lists or list-like objects.
如上面的例子所示,FOR-IN-ZIP循环在循环变量和值之间需要自己的自定义分隔符IN ZIP(区分大小写)。与FOR-IN-ZIP循环一起使用的值必须是列表或类似列表的对象。

Items to iterate over must always be given either as scalar variables like ${items} or as list variables like @{lists} that yield the actual iterated lists. The former approach is more common and it was already demonstrated above. The latter approach works like this:
要迭代的项必须始终以标量变量(如${items})或列表变量(如@{lists})的形式给出,以生成实际的迭代列表。前一种方法更常见,上面已经演示过。后一种方法的工作原理如下:

*** Variables ***
@{NUMBERS}       ${1}    ${2}    ${5}
@{NAMES}         one     two     five
@{LISTS}         ${NUMBERS}    ${NAMES}

*** Test Cases ***
FOR-IN-ZIP with lists from variable
    FOR    ${number}    ${name}    IN ZIP    @{LISTS}
        Log Many    ${number}    ${name}
    END

The number of lists to iterate over is not limited, but it must match the number of loop variables. Alternatively, there can be just one loop variable that then becomes a Python tuple getting items from all lists.
要遍历的列表的数量没有限制,但它必须与循环变量的数量相匹配。或者,可以只有一个循环变量,然后变成一个从所有列表中获取项目的Python元组。

*** Variables ***
@{ABC}           a    b    c
@{XYZ}           x    y    z
@{NUM}           1    2    3

*** Test Cases ***
FOR-IN-ZIP with multiple lists
    FOR    ${a}    ${x}    ${n}    IN ZIP    ${ABC}    ${XYZ}    ${NUM}
        Log Many    ${a}    ${x}    ${n}
    END

FOR-IN-ZIP with one variable
    FOR    ${items}    IN ZIP    ${ABC}    ${XYZ}    ${NUM}
        Length Should Be    ${items}    3
        Log Many    ${items}[0]    ${items}[1]    ${items}[2]
    END

Starting from Robot Framework 6.1, it is possible to configure what to do if lengths of the iterated items differ. By default, the shortest item defines how many iterations there are and values at the end of longer ones are ignored. This can be changed by using the mode option that has three possible values:
从Robot Framework 6.1开始,可以配置迭代项的长度不同时的操作。默认情况下,最短项定义有多少次迭代,而较长项末尾的值将被忽略。这可以通过使用mode选项来更改,该选项有三个可能的值:

  • STRICT: Items must have equal lengths. If not, execution fails. This is the same as using strict=True with Python's zip function.
    严格:项目必须具有相等的长度。否则,执行失败。这与在Python的zip函数中使用strict=True相同。
  • SHORTEST: Items in longer items are ignored. Infinite iterators are supported in this mode as long as one of the items is exhausted. This is the default behavior.
    SHORTEST:忽略较长项目中的项目。在这种模式下,只要其中一个项用完,就支持无限迭代器。这是默认行为。
  • LONGEST: The longest item defines how many iterations there are. Missing values in shorter items are filled-in with value specified using the fill option or None if it is not used. This is the same as using Python's zip_longest function except that it has fillvalue argument instead of fill.
    LONGEST:最长的项目定义了有多少次迭代。较短项中的缺失值将使用填充选项指定的值填充,如果未使用则使用无。这与使用Python的zip_longest函数是一样的,除了它有fillvalue参数而不是fill

All these modes are illustrated by the following examples:
所有这些模式都通过以下示例来说明:

*** Variables ***
@{CHARACTERS}     a    b    c    d    f
@{NUMBERS}        1    2    3

*** Test Cases ***
STRICT mode
    [Documentation]    This loop fails due to lists lengths being different.
    FOR    ${c}    ${n}    IN ZIP    ${CHARACTERS}    ${NUMBERS}    mode=STRICT
        Log    ${c}: ${n}
    END

SHORTEST mode
    [Documentation]    This loop executes three times.
    FOR    ${c}    ${n}    IN ZIP    ${CHARACTERS}    ${NUMBERS}    mode=SHORTEST
        Log    ${c}: ${n}
    END

LONGEST mode
    [Documentation]    This loop executes five times.
    ...                On last two rounds `${n}` has value `None`.
    FOR    ${c}    ${n}    IN ZIP    ${CHARACTERS}    ${NUMBERS}    mode=LONGEST
        Log    ${c}: ${n}
    END

LONGEST mode with custom fill value
    [Documentation]    This loop executes five times.
    ...                On last two rounds `${n}` has value `0`.
    FOR    ${c}    ${n}    IN ZIP    ${CHARACTERS}    ${NUMBERS}    mode=LONGEST    fill=0
        Log    ${c}: ${n}
    END

Note 注意

The behavior if list lengths differ will change in the future so that the STRICT mode will be the default. If that is not desired, the SHORTEST mode needs to be used explicitly.
如果列表长度不同的行为将在将来改变,因此STRICT模式将成为默认模式。如果不希望这样,则需要显式地使用SHORTEST模式。

Dictionary iteration 字典迭代

Normal FOR loops and FOR-IN-ENUMERATE loops support iterating over keys and values in dictionaries. This syntax requires at least one of the loop values to be a dictionary variable. It is possible to use multiple dictionary variables and to give additional items in key=value syntax. Items are iterated in the order they are defined and if same key gets multiple values the last value will be used.
普通的FOR循环和FOR-IN-ENUMERATE循环支持遍历字典中的键和值。此语法要求至少有一个循环值是字典变量。可以使用多个字典变量,并在key=value语法中给出额外的项。项目是按照定义的顺序迭代的,如果同一个键获得多个值,则将使用最后一个值。

*** Variables ***
&{DICT}          a=1    b=2    c=3

*** Test Cases ***
Dictionary iteration with FOR loop
    FOR    ${key}    ${value}    IN    &{DICT}
        Log    Key is '${key}' and value is '${value}'.
    END

Dictionary iteration with FOR-IN-ENUMERATE loop
    FOR    ${index}    ${key}    ${value}    IN ENUMERATE    &{DICT}
        Log    On round ${index} key is '${key}' and value is '${value}'.
    END

Multiple dictionaries and extra items in 'key=value' syntax
    &{more} =    Create Dictionary    e=5    f=6
    FOR    ${key}    ${value}    IN    &{DICT}    d=4    &{more}    g=7
        Log    Key is '${key}' and value is '${value}'.
    END

Typically it is easiest to use the dictionary iteration syntax so that keys and values get separate variables like in the above examples. With normal FOR loops it is also possible to use just a single variable that will become a tuple containing the key and the value. If only one variable is used with FOR-IN-ENUMERATE loops, it becomes a tuple containing the index, the key and the value. Two variables with FOR-IN-ENUMERATE loops means assigning the index to the first variable and making the second variable a tuple containing the key and the value.
通常,最简单的方法是使用字典迭代语法,以便键和值获得单独的变量,就像上面的示例一样。对于普通的FOR循环,也可以只使用一个变量,它将成为一个包含键和值的元组。如果FOR-IN-ENUMERATE循环中只使用一个变量,它将成为一个包含索引、键和值的元组。使用FOR-IN-ENUMERATE循环的两个变量意味着将索引赋给第一个变量,并使第二个变量成为包含键和值的元组。

*** Test Cases ***
One loop variable
    FOR    ${item}    IN    &{DICT}
        Log    Key is '${item}[0]' and value is '${item}[1]'.
    END

One loop variable with FOR-IN-ENUMERATE
    FOR    ${item}    IN ENUMERATE    &{DICT}
        Log    On round ${item}[0] key is '${item}[1]' and value is '${item}[2]'.
    END

Two loop variables with FOR-IN-ENUMERATE
    FOR    ${index}    ${item}    IN ENUMERATE    &{DICT}
        Log    On round ${index} key is '${item}[0]' and value is '${item}[1]'.
    END

In addition to iterating over names and values in dictionaries, it is possible to iterate over keys and then possibly fetch the value based on it. This syntax requires using dictionaries as list variables:
除了迭代字典中的名称和值之外,还可以遍历键,然后可能基于它获取值。这种语法需要使用字典作为列表变量

*** Test Cases ***
Iterate over keys
    FOR    ${key}    IN    @{DICT}
        Log    Key is '${key}' and value is '${DICT}[${key}]'.
    END

Note 注意

Iterating over keys and values in dictionaries is a new feature in Robot Framework 3.2. With earlier version it is possible to iterate over dictionary keys like the last example above demonstrates.
迭代字典中的键和值是Robot Framework 3.2中的新功能。在早期版本中,可以像上面的最后一个例子演示的那样覆盖字典键。

Removing unnecessary keywords from outputs
从输出中删除不必要的关键字

FOR loops with multiple iterations often create lots of output and considerably increase the size of the generated output and log files. It is possible to remove or flatten unnecessary keywords using --removekeywords and --flattenkeywords command line options.
具有多次迭代的FOR循环通常会创建大量输出,并显著增加生成的输出日志文件的大小。可以使用--removekeywords--removekeywords命令行选项删除或扁平化不必要的关键字

Repeating single keyword 重复单个关键字

FOR loops can be excessive in situations where there is only a need to repeat a single keyword. In these cases it is often easier to use BuiltIn keyword Repeat Keyword. This keyword takes a keyword and how many times to repeat it as arguments. The times to repeat the keyword can have an optional postfix times or x to make the syntax easier to read.
在只需要重复一个关键字的情况下,FOR循环可能会过多。在这些情况下,使用BuiltIn关键字Repeat Keyword通常更容易。此关键字接受一个关键字以及将其重复多少次作为参数。重复关键字的次数可以有一个可选的后缀timesx,以使语法更容易阅读。

*** Test Cases ***
Example
    Repeat Keyword    5    Some Keyword    arg1    arg2
    Repeat Keyword    42 times    My Keyword
    Repeat Keyword    ${var}    Another Keyword    argument

2.9.2   WHILE loops
2.9.2WHILE循环

WHILE loops combine features of FOR loops and IF/ELSE structures. They specify a condition and repeat the loop body as long as the condition remains true. This can be utilised, for example, to repeat a nondeterministic sequence until the desired outcome happens, or in some cases they can be used as an alternative to FOR loops.
WHILE循环结合了FOR循环IF/ELSE结构的联合收割机特性。它们指定一个条件,只要条件保持为真,就重复循环体。例如,这可以用来重复一个不确定的序列,直到所需的结果发生,或者在某些情况下,它们可以用作FOR循环的替代方案。

Note 注意

WHILE loops are new in Robot Framework 5.0.
WHILE循环是Robot Framework 5.0中的新功能。

Basic WHILE syntax
基本WHILE语法

*** Test Cases ***
Example
    VAR    ${rc}   1
    WHILE    ${rc} != 0
        ${rc} =    Keyword that returns zero on success
    END

The WHILE loop condition is evaluated in Python so that Python builtins like len() are available and modules are imported automatically to support usages like math.pi * math.pow(${radius}, 2) < 10. Normal variables like ${rc} in the above example are replaced before evaluation, but variables are also available in the evaluation namespace using the special $rc syntax. The latter approach is handy when the string representation of the variable cannot be used in the condition directly. For example, strings require quoting and multiline strings and string themselves containing quotes cause additional problems. See the Evaluating expressions appendix for more information and examples related to the evaluation syntax.
WHILE循环条件在Python中进行计算,这样Python内置的len()就可用了,并且模块会自动导入以支持math.pi * math.pow(${radius},2)等用法< 10。在上面的例子中,像${rc}这样的普通变量在求值之前被替换,但是变量也可以使用特殊的$rc语法在求值命名空间中使用。当变量的字符串表示不能直接用于条件时,后一种方法很方便。例如,字符串需要引号,多行字符串和字符串本身包含引号会导致其他问题。有关求值语法的更多信息和示例,请参见求值表达式附录。

Starting from Robot Framework 6.1, the condition in a WHILE statement can be omitted. This is interpreted as the condition always being true, which may be useful with the limit option described below.
从Robot Framework 6.1开始,WHILE语句中的条件可以省略。这被解释为条件总是为真,这对于下面描述的限制选项可能很有用。

Limiting WHILE loop iterations
限制WHILE循环迭代

With WHILE loops, there is always a possibility to achieve an infinite loop, either by intention or by mistake. This happens when the loop condition never becomes false. While infinite loops have some utility in application programming, in automation an infinite loop is rarely a desired outcome. If such a loop occurs with Robot Framework, the execution must be forcefully stopped and no log or report can be created. For this reason, WHILE loops in Robot Framework have a default limit of 10 000 iterations. If the limit is exceeded, the loop fails.
使用WHILE循环,总是有可能实现无限循环,无论是有意还是无意。当循环条件永远不会变为false时,就会发生这种情况。虽然无限循环在应用程序编程中有一定的实用性,但在自动化中,无限循环很少是理想的结果。如果Robot Framework发生此类循环,则必须强制停止执行,并且无法创建日志或报告。因此,Robot Framework中的WHILE循环默认限制为10000次迭代。如果超过限制,则循环失败。

The limit can be set with the limit configuration parameter either as a maximum iteration count or as a maximum time for the whole loop. When the limit is an iteration count, it is possible to use just integers like 100 and to add times or x suffix after the value like 100 times. When the limit is a timeout, it is possible to use time strings like 10 s or 1 hour 10 minutes. The limit can also be disabled altogether by using NONE (case-insensitive). All these options are illustrated by the examples below.
可以使用limit配置参数将限制设置为最大迭代计数或整个循环的最大时间。当限制是迭代次数时,可以只使用整数,如100,并在值后添加x后缀,如100倍。当限制是超时时,可以使用时间字符串,如10秒1小时10分钟。也可以使用NONE(不区分大小写)完全禁用该限制。所有这些选项都通过下面的例子来说明。

*** Test Cases ***
Limit as iteration count
    WHILE    True    limit=100
        Log    This is run 100 times.
    END
    WHILE    True    limit=10 times
        Log    This is run 10 times.
    END
    WHILE    True    limit=42x
        Log    This is run 42 times.
    END

Limit as time
    WHILE    True    limit=10 seconds
        Log    This is run 10 seconds.
    END

No limit
    WHILE    True    limit=NONE
        Log    This runs forever.
    END

Note 注意

Support for using times and x suffixes with iteration counts is new in Robot Framework 7.0.
Robot Framework 7.0中新增了对使用带有迭代计数的时间x后缀的支持。

Keywords in a loop are not forcefully stopped if the limit is exceeded. Instead the loop is exited similarly as if the loop condition would have become false. A major difference is that the loop status will be FAIL in this case.
如果超过限制,则不会强制停止循环中的关键字。相反,循环会以类似的方式退出,就好像循环条件会变成false一样。一个主要的区别是,在这种情况下,循环状态将为FAIL

Starting from Robot Framework 6.1, it is possible to use on_limit parameter to configure the behaviour when the limit is exceeded. It supports two values pass and fail, case insensitively. If the value is pass, the execution will continue normally when the limit is reached and the status of the WHILE loop will be PASS. The value fail works similarly as the default behaviour, e.g. the loop and the test will fail if the limit is exceeded.
从Robot Framework 6.1开始,可以使用on_limit参数来配置超过限制时的行为。它支持两个值passfail,不区分大小写。如果该值为pass,则当达到限制时,执行将正常继续,并且WHILE循环的状态将为PASS。值fail的工作方式与默认行为类似,例如,如果超过限制,则循环和测试将失败。

*** Test Cases ***
Continue when iteration limit is reached
    WHILE    True    limit=5    on_limit=pass
        Log    Loop will be executed five times
    END
    Log    This will be executed normally.

Continue when time limit is reached
    WHILE    True    limit=10s    on_limit=pass
        Log    Loop will be executed for 10 seconds.
        Sleep   0.5s
    END
    Log    This will be executed normally.

By default, the error message raised when the limit is reached is WHILE loop was aborted because it did not finish within the limit of 0.5 seconds. Use the 'limit' argument to increase or remove the limit if needed.. Starting from Robot Framework 6.1, the error message can be changed with the on_limit_message configuration parameter.
默认情况下,达到限制时引发的错误消息是WHILE循环被中止,因为它没有在0.5秒的限制内完成。如果需要,可以使用“limit”参数来增加或删除限制。.从Robot Framework 6.1开始,可以使用on_limit_message配置参数更改错误消息。

*** Test Cases ***
Limit as iteration count
    WHILE    True    limit=0.5s    on_limit_message=Custom While loop error message
        Log    This is run 0.5 seconds.
    END

Note 注意

on_limit_message configuration parameter is new in Robot Framework 6.1.
on_limit_message配置参数是Robot Framework 6.1中的新参数。

Nesting WHILE loops
嵌套WHILE循环

WHILE loops can be nested and also combined with other control structures:
WHILE循环可以嵌套,也可以与其他控制结构组合:

*** Test Cases ***
Nesting WHILE
    ${x} =   Set Variable    10
    WHILE    ${x} > 0
        ${y} =   Set Variable    ${x}
        WHILE    ${y} > 0
            ${y} =    Evaluate    ${y} - 1
        END
        IF    ${x} > 5
            ${x} =    Evaluate    ${x} - 1
        ELSE
            ${x} =    Evaluate    ${x} - 2
        END
    END

Removing unnecessary keywords from outputs
从输出中删除不必要的关键字

WHILE loops with multiple iterations often create lots of output and considerably increase the size of the generated output and log files. It is possible to remove or flatten unnecessary keywords using --removekeywords and --flattenkeywords command line options.
具有多次迭代的WHILE循环通常会创建大量输出,并显著增加生成的输出日志文件的大小。可以使用--removekeywords--removekeywords命令行选项删除或扁平化不必要的关键字

2.9.3   Loop control using BREAK and CONTINUE
2.9.3使用BREAKCONTINUE的循环控制

Both FOR and WHILE loop execution can be controlled with BREAK and CONTINUE statements. The former exits the whole loop prematurely and the latter stops executing the current loop iteration and continues to the next one. In practice they have the same semantics as break and continue statements in Python, Java, and many other programming languages.
FORWHILE循环的执行都可以用BREAKCONTINUE语句控制。前者过早地退出整个循环,后者停止执行当前循环迭代并继续下一个循环。在实践中,它们与Python、Java和许多其他编程语言中的breakcontinue语句具有相同的语义。

Both BREAK and CONTINUE are typically used conditionally with IF/ELSE or TRY/EXCEPT structures, and especially the inline IF syntax is often convenient with them. These statements must be used in the loop body, possibly inside the aforementioned control structures, and using them in keyword called in the loop body is invalid.
BREAKCONTINUE通常与IF/ELSETRY/EXCEPT结构一起有条件地使用,特别是内联IF语法通常很方便。这些语句必须在循环体中使用,可能在上述控制结构中使用,并且在循环体中调用的关键字中使用它们无效。

*** Test Cases ***
BREAK with FOR
    ${text} =    Set Variable    zero
    FOR    ${var}    IN    one    two    three
        IF    '${var}' == 'two'    BREAK
        ${text} =    Set Variable    ${text}-${var}
    END
    Should Be Equal    ${text}    zero-one

CONTINUE with FOR
    ${text} =    Set Variable    zero
    FOR    ${var}    IN    one    two    three
        IF    '${var}' == 'two'    CONTINUE
        ${text} =    Set Variable    ${text}-${var}
    END
    Should Be Equal    ${text}    zero-one-three

CONTINUE and BREAK with WHILE
    WHILE    True
        TRY
             ${value} =    Do Something
        EXCEPT
            CONTINUE
        END
        Do something with value    ${value}
        BREAK
    END

Invalid BREAK usage
    [Documentation]    BREAK and CONTINUE can only be used in the loop body,
    ...                not in keywords used in the loop.
    FOR    ${var}    IN    one    two    three
        Invalid BREAK
    END

*** Keywords ***
Invalid BREAK
    [Documentation]    This keyword fails due to invalid syntax.
    BREAK

Note 注意

BREAK and CONTINUE statements are new in Robot Framework 5.0 similarly as WHILE. Earlier versions supported controlling FOR loops using BuiltIn keywords Exit For Loop, Exit For Loop If, Continue For Loop and Continue For Loop If. These keywords still continue to work, but they will be deprecated and removed in the future.
BREAKCONTINUE语句是Robot Framework 5.0中新增的,与WHILE类似。早期版本支持使用内置关键字Exit For LoopExit For Loop IfContinue For LoopContinue For Loop If来控制FOR循环。这些关键字仍然有效,但它们将在未来被弃用和删除。

Note 注意

Also the RETURN statement can be used to a exit loop. It only works when loops are used inside a user keyword.
RETURN语句也可以用于退出循环。它只在循环在user关键字中使用时有效。

2.9.4   IF/ELSE syntax
2.9.4IF/ELSE语法

Sometimes there is a need to execute some keywords conditionally. Starting from Robot Framework 4.0 there is a separate IF/ELSE syntax, but there are also other ways to execute keywords conditionally. Notice that if the logic gets complicated, it is typically better to move it into a test library.
有时需要有条件地执行某些关键字。从Robot Framework 4.0开始,有一个单独的IF/ELSE语法,但也有其他方式来有条件地执行关键字。请注意,如果逻辑变得复杂,通常最好将其移到测试库中。

Basic IF syntax
基本IF语法

Robot Framework's native IF syntax starts with IF (case-sensitive) and ends with END (case-sensitive). The IF marker requires exactly one value that is the condition to evaluate. Keywords to execute if the condition is true are on their own rows between the IF and END markers. Indenting keywords in the IF block is highly recommended but not mandatory.
Robot Framework的本机IF语法以IF(区分大小写)开始,以END(区分大小写)结束。IF标记只需要一个值作为要计算的条件。如果条件为真,则要执行的关键字位于IFEND标记之间的行中。强烈建议在IF块中缩进关键字,但不是强制性的。

In the following example keywords Some keyword and Another keyword are executed if ${rc} is greater than zero:
在以下示例中,如果${rc}大于零,则执行keywords Some keywordAnother keyword

*** Test Cases ***
Example
   IF    ${rc} > 0
       Some keyword
       Another keyword
   END

The condition is evaluated in Python so that Python builtins like len() are available and modules are imported automatically to support usages like platform.system() == 'Linux' and math.ceil(${x}) == 1. Normal variables like ${rc} in the above example are replaced before evaluation, but variables are also available in the evaluation namespace using the special $rc syntax. The latter approach is handy when the string representation of the variable cannot be used in the condition directly. For example, strings require quoting and multiline strings and string themselves containing quotes cause additional problems. For more information and examples related the evaluation syntax see the Evaluating expressions appendix.
该条件在Python中进行计算,以便像len()这样的Python内置函数可用,并且模块自动导入以支持像platform.system()== 'Linux'math.ceil(${x})== 1这样的用法。在上面的例子中,像${rc}这样的普通变量在求值之前被替换,但是变量也可以使用特殊的$rc语法在求值命名空间中使用。当变量的字符串表示不能直接用于条件时,后一种方法很方便。例如,字符串需要引号,多行字符串和字符串本身包含引号会导致其他问题。有关计算语法的更多信息和示例,请参见附录“计算表达式”

ELSE branches
ELSE分支

Like most other languages supporting conditional execution, Robot Framework IF syntax also supports ELSE branches that are executed if the IF condition is not true.
与大多数支持条件执行的其他语言一样,Robot FrameworkIF语法也支持在IF条件不为真时执行的ELSE分支。

In this example Some keyword is executed if ${rc} is greater than zero and Another keyword is executed otherwise:
在本例中,如果${rc}大于零,则执行Some关键字,否则执行Another关键字

*** Test Cases ***
Example
    IF    ${rc} > 0
        Some keyword
    ELSE
        Another keyword
    END

ELSE IF branches
ELSE IF分支

Robot Framework also supports ELSE IF branches that have their own condition that is evaluated if the initial condition is not true. There can be any number of ELSE IF branches and they are gone through in the order they are specified. If one of the ELSE IF conditions is true, the block following it is executed and remaining ELSE IF branches are ignored. An optional ELSE branch can follow ELSE IF branches and it is executed if all conditions are false.
Robot Framework还支持ELSE IF分支,这些分支具有自己的条件,如果初始条件不为真,则会对其进行评估。可以有任意数量的ELSE IF分支,它们按照指定的顺序进行。如果其中一个ELSE IF条件为真,则执行它后面的块,并忽略其余的ELSE IF分支。可选的ELSE分支可以跟在ELSE IF分支之后,如果所有条件都为假,则执行该分支。

In the following example different keyword is executed depending on is ${rc} positive, negative, zero, or something else like a string or None:
在下面的示例中,根据${rc}是正数、负数、零还是字符串或None之类的其他值来执行不同的关键字:

*** Test Cases ***
Example
    IF    $rc > 0
        Positive keyword
    ELSE IF    $rc < 0
        Negative keyword
    ELSE IF    $rc == 0
        Zero keyword
    ELSE
        Fail    Unexpected rc: ${rc}
    END

Notice that this example uses the ${rc} variable in the special $rc format to avoid evaluation failures if it is not a number. See the aforementioned Evaluating expressions appendix for more information about this syntax.
请注意,此示例使用特殊$rc格式的${rc}变量,以避免在它不是数字时计算失败。有关此语法的更多信息,请参见前面的Evaluating expressions附录。

Inline IF
内嵌IF

Normal IF/ELSE structure is a bit verbose if there is a need to execute only a single statement. An alternative to it is using inline IF syntax where the statement to execute follows the IF marker and condition directly and no END marker is needed. For example, the following two keywords are equivalent:
如果只需要执行一条语句,那么普通的IF/ELSE结构就有点冗长。另一种方法是使用内联IF语法,其中要执行的语句直接跟随IF标记和条件,而不需要END标记。例如,以下两个关键字是等效的:

*** Keywords ***
Normal IF
    IF    $condition1
        Keyword    argument
    END
    IF    $condition2
        RETURN
    END

Inline IF
    IF    $condition1    Keyword    argument
    IF    $condition2    RETURN

The inline IF syntax supports also ELSE and ELSE IF branches:
内联IF语法还支持ELSEELSE IF分支:

*** Keywords ***
Inline IF/ELSE
    IF    $condition    Keyword    argument    ELSE    Another Keyword

Inline IF/ELSE IF/ELSE
    IF    $cond1    Keyword 1    ELSE IF    $cond2    Keyword 2    ELSE IF    $cond3    Keyword 3    ELSE    Keyword 4

As the latter example above demonstrates, inline IF with several ELSE IF and ELSE branches starts to get hard to understand. Long inline IF structures can be split into multiple lines using the common ... continuation syntax, but using a normal IF/ELSE structure or moving the logic into a test library is probably a better idea. Each inline IF branch can contain only one statement. If more statements are needed, normal IF/ELSE structure needs to be used instead.
正如上面的后一个例子所展示的,带有几个ELSE IFELSE分支的内联IF开始变得难以理解。长内联IF结构可以使用常见的... continuation语法,但使用普通的IF/ELSE结构或将逻辑移动到测试库中可能是更好的主意。每个内联IF分支只能包含一条语句。如果需要更多的语句,则需要使用普通的IF/ELSE结构。

If there is a need for an assignment with inline IF, the variable or variables to assign must be before the starting IF. Otherwise the logic is exactly the same as when assigning variables based on keyword return values. If assignment is used and no branch is run, the variable gets value None.
如果需要使用内联IF进行赋值,则要赋值的一个或多个变量必须在起始IF之前。否则,逻辑与基于关键字返回值分配变量时完全相同。如果使用了赋值并且没有运行任何分支,则变量的值为None

*** Keywords ***
Inline IF/ELSE with assignment
    ${var} =    IF    $condition    Keyword    argument    ELSE    Another Keyword

Inline IF/ELSE with assignment having multiple variables
    ${host}    ${port} =    IF    $production    Get Production Config    ELSE    Get Testing Config

Note 注意

Inline IF syntax is new in Robot Framework 5.0.
内联IF语法是Robot Framework 5.0中的新语法。

Nested IF structures
嵌套IF结构

IF structures can be nested with each others and with FOR loops. This is illustrated by the following example using advanced features such as FOR-IN-ENUMERATE loop, named-only arguments with user keywords and inline Python evaluation syntax (${{len(${items})}}):
IF结构可以彼此嵌套,也可以与FOR循环嵌套。以下示例使用高级功能(如FOR-IN-ENUMERATE循环带用户关键字的仅命名参数内联Python求值语法(${{len(${items})}}))说明了这一点:

*** Keywords ***
Log items
    [Arguments]    @{items}    ${log_values}=True
    IF    not ${items}
        Log to console    No items.
    ELSE IF    len(${items}) == 1
        IF    ${log_values}
            Log to console    One item: ${items}[0]
        ELSE
            Log to console    One item.
        END
    ELSE
        Log to console    ${{len(${items})}} items.
        IF    ${log_values}
            FOR    ${index}    ${item}    IN ENUMERATE    @{items}    start=1
                Log to console    Item ${index}: ${item}
            END
        END
    END

*** Test Cases ***
No items
    Log items

One item without logging value
    Log items    xxx    log_values=False

Multiple items
    Log items    a    b    c

Other ways to execute keywords conditionally
有条件地执行关键字的其他方法

There are also other methods to execute keywords conditionally:
还有其他方法可以有条件地执行关键字:

  • The name of the keyword used as a setup or a teardown with suites, tests and keywords can be specified using a variable. This facilitates changing them, for example, from the command line.
    可以使用变量指定用于设置或拆卸套件测试关键字的关键字的名称。这有助于更改它们,例如,从命令行。
  • The BuiltIn keyword Run Keyword takes a keyword to actually execute as an argument and it can thus be a variable. The value of the variable can, for example, be got dynamically from an earlier keyword or given from the command line.
    内置关键字Run Keyword将一个关键字作为参数实际执行,因此它可以是一个变量。例如,变量的值可以从前面的关键字动态获取或从命令行给定。
  • The BuiltIn keywords Run Keyword If and Run Keyword Unless execute a named keyword only if a certain expression is true or false, respectively. The new IF/ELSE syntax explained above is generally recommended, though.
    内置关键字Run Keyword IfRun Keyword Unless仅在特定表达式分别为true或false时执行命名关键字。不过,通常建议使用上面解释的新IF/ELSE语法。
  • Another BuiltIn keyword, Set Variable If, can be used to set variables dynamically based on a given expression.
    另一个内置关键字Set Variable If可用于根据给定表达式动态设置变量。
  • There are several BuiltIn keywords that allow executing a named keyword only if a test case or test suite has failed or passed.
    有几个内置关键字允许仅在测试用例或测试套件失败或通过时执行命名关键字。

2.9.5   TRY/EXCEPT syntax
2.9.5TRY/EXCEPT语法

When a keyword fails, Robot Framework's default behavior is to stop the current test and executes its possible teardown. There can, however, be needs to handle these failures during execution as well. Robot Framework 5.0 introduces native TRY/EXCEPT syntax for this purpose, but there also other ways to handle errors.
当关键字失败时,Robot Framework的默认行为是停止当前测试并执行其可能的拆除。然而,在执行期间也可能需要处理这些故障。Robot Framework 5.0为此引入了原生TRY/EXCEPT语法,但也有其他方法来处理错误

Robot Framework's TRY/EXCEPT syntax is inspired by Python's exception handling syntax. It has same TRY, EXCEPT, ELSE and FINALLY branches as Python and they also mostly work the same way. A difference is that Python uses lower case try, except, etc. but with Robot Framework all this kind of syntax must use upper case letters. A bigger difference is that with Python exceptions are objects and with Robot Framework you are dealing with error messages as strings.
Robot Framework的TRY/EXCEPT语法受到Python异常处理语法的启发。它有与Python相同的TRYEXCEPTELSEFINALLY分支,它们的工作方式也基本相同。不同之处在于Python使用小写的tryexcept等,但在Robot Framework中,所有此类语法都必须使用大写字母。一个更大的区别是,在Python中,异常是对象,而在Robot Framework中,错误消息是字符串。

Catching exceptions with EXCEPT
使用EXCEPT捕获异常

The basic TRY/EXCEPT syntax can be used to handle failures based on error messages:
基本的TRY/EXCEPT语法可用于根据错误消息处理失败:

*** Test Cases ***
First example
    TRY
        Some Keyword
    EXCEPT    Error message
        Error Handler Keyword
    END
    Keyword Outside

In the above example, if Some Keyword passes, the EXCEPT branch is not run and execution continues after the TRY/EXCEPT structure. If the keyword fails with a message Error message (case-sensitive), the EXCEPT branch is executed. If the EXCEPT branch succeeds, execution continues after the TRY/EXCEPT structure. If it fails, the test fails and remaining keywords are not executed. If Some Keyword fails with any other exception, that failure is not handled and the test fails without executing remaining keywords.
在上面的示例中,如果Some Keyword通过,则EXCEPT分支不运行,并且在TRY/EXCEPT结构之后继续执行。如果关键字失败并显示错误消息(区分大小写),则执行EXCEPT分支。如果EXCEPT分支成功,则在TRY/EXCEPT结构之后继续执行。如果失败,则测试失败,其余关键字将不执行。如果Some Keyword失败,但出现任何其他异常,则不会处理该失败,并且测试将失败,而不会执行剩余的关键字。

There can be more than one EXCEPT branch. In that case they are matched one by one and the first matching branch is executed. One EXCEPT can also have multiple messages to match, and such a branch is executed if any of its messages match. In all these cases messages can be specified using variables in addition to literal strings.
可以有多个EXCEPT分支。在这种情况下,它们一个接一个地匹配,并且执行第一匹配分支。一个EXCEPT也可以有多个消息要匹配,如果其中任何消息匹配,则执行这样的分支。在所有这些情况下,除了文字字符串之外,还可以使用变量来指定消息。

*** Test Cases ***
Multiple EXCEPT branches
    TRY
        Some Keyword
    EXCEPT    Error message    # Try matching this first.
        Error Handler 1
    EXCEPT    Another error    # Try this if above did not match.
        Error Handler 2
    EXCEPT    ${message}       # Last match attempt, this time using a variable.
        Error Handler 3
    END

Multiple messages with one EXCEPT
    TRY
        Some Keyword
    EXCEPT    Error message    Another error    ${message}    # Match any of these.
        Error handler
    END

It is also possible to have an EXCEPT without messages, in which case it matches any error. There can be only one such EXCEPT and it must follow possible other EXCEPT branches:
也可以有一个没有消息的EXCEPT,在这种情况下,它匹配任何错误。只能有一个这样的EXCEPT,它必须遵循可能的其他EXCEPT分支:

*** Test Cases ***
Match any error
    TRY
        Some Keyword
    EXCEPT               # Match any error.
        Error Handler
    END

Match any after testing more specific errors
    TRY
        Some Keyword
    EXCEPT    Error message    # Try matching this first
        Error Handler 1
    EXCEPT                     # Match any that did not match the above.
        Error Handler 2
    END

Note 注意

It is not possible to catch exceptions caused by invalid syntax.
不可能捕获由无效语法引起的异常。

Matching errors using patterns
使用模式匹配错误

By default matching an error using EXCEPT requires an exact match. That can be changed using a configuration option type= as an argument to the except clause. Valid values for the option are GLOB, REGEXP or START (case-insensitive) to make the match a glob pattern match, a regular expression match, or to match only the beginning of the error, respectively. Using value LITERAL has the same effect as the default behavior. If an EXCEPT has multiple messages, this option applies to all of them. The value of the option can be defined with a variable as well.
默认情况下,使用EXCEPT匹配错误需要精确匹配。可以使用配置选项type=作为except子句的参数来更改。该选项的有效值为GLOBREGEXPSTART(不区分大小写),分别用于使匹配为glob模式匹配正则表达式匹配或仅匹配错误的开头。使用值LITERAL与默认行为具有相同的效果。如果EXCEPT有多个消息,则此选项适用于所有消息。选项的值也可以用变量定义。

*** Variables ***
${MATCH TYPE}     regexp

*** Test Cases ***
Glob pattern
    TRY
        Some Keyword
    EXCEPT    ValueError: *    type=GLOB
        Error Handler 1
    EXCEPT    [Ee]rror ?? occurred    ${pattern}    type=glob
        Error Handler 2
    END

Regular expression
    TRY
        Some Keyword
    EXCEPT    ValueError: .*    type=${MATCH TYPE}
        Error Handler 1
    EXCEPT    [Ee]rror \\d+ occurred    type=Regexp    # Backslash needs to be escaped.
        Error Handler 2
    END

Match start
    TRY
        Some Keyword
    EXCEPT    ValueError:    ${beginning}    type=start
        Error Handler
    END

Explicit exact match
    TRY
        Some Keyword
    EXCEPT    ValueError: invalid literal for int() with base 10: 'ooops'    type=LITERAL
        Error Handler
    EXCEPT    Error 13 occurred    type=LITERAL
        Error Handler 2
    END

Note 注意

Remember that the backslash character often used with regular expressions is an escape character in Robot Framework data. It thus needs to be escaped with another backslash when using it in regular expressions.
请记住,经常与正则表达式一起使用的反斜杠字符是Robot Framework数据中的转义字符。因此,在正则表达式中使用它时,需要用另一个反斜杠进行转义。

Capturing error message 捕获错误消息

When matching errors using patterns and when using EXCEPT without any messages to match any error, it is often useful to know the actual error that occurred. Robot Framework supports that by making it possible to capture the error message into a variable by adding AS  ${var} at the end of the EXCEPT statement:
使用模式匹配错误时,以及当使用EXCEPT而不使用任何消息匹配任何错误时,了解实际发生的错误通常很有用。Robot Framework通过在EXCEPT语句的末尾添加AS ${var}来将错误消息捕获到变量中,从而支持此操作:

*** Test Cases ***
Capture error
    TRY
        Some Keyword
    EXCEPT    ValueError: *    type=GLOB    AS   ${error}
        Error Handler 1    ${error}
    EXCEPT    [Ee]rror \\d+    (Invalid|Bad) usage    type=REGEXP    AS    ${error}
        Error Handler 2    ${error}
    EXCEPT    AS    ${error}
        Error Handler 3    ${error}
    END

Using ELSE to execute keywords when there are no errors
使用ELSE在没有错误的情况下执行关键字

Optional ELSE branches make it possible to execute keywords if there is no error. There can be only one ELSE branch and it is allowed only after one or more EXCEPT branches:
可选的ELSE分支使得在没有错误的情况下执行关键字成为可能。只能有一个ELSE分支,并且只允许在一个或多个EXCEPT分支之后使用:

*** Test Cases ***
ELSE branch
    TRY
        Some Keyword
    EXCEPT    X
        Log    Error 'X' occurred!
    EXCEPT    Y
        Log    Error 'Y' occurred!
    ELSE
        Log    No error occurred!
    END
    Keyword Outside

In the above example, if Some Keyword passes, the ELSE branch is executed, and if it fails with message X or Y, the appropriate EXCEPT branch run. In all these cases execution continues after the whole TRY/EXCEPT/ELSE structure. If Some Keyword fail any other way, EXCEPT and ELSE branches are not run and the TRY/EXCEPT/ELSE structure fails.
在上面的示例中,如果Some Keyword通过,则执行ELSE分支,如果失败并显示消息XY,则运行相应的EXCEPT分支。在所有这些情况下,执行在整个TRY/EXCEPT/ELSE结构之后继续。如果Some Keyword以任何其他方式失败,则EXCEPTELSE分支不会运行,并且TRY/EXCEPT/ELSE结构失败。

To handle both the case when there is any error and when there is no error, it is possible to use an EXCEPT without any message in combination with an ELSE:
为了处理有错误和没有错误的情况,可以将EXCEPTELSE结合使用,而不带任何消息:

*** Test Cases ***
Handle everything
    TRY
        Some Keyword
    EXCEPT    AS    ${err}
        Log    Error occurred: ${err}
    ELSE
        Log    No error occurred!
    END

Using FINALLY to execute keywords regardless are there errors or not
使用FINALLY执行关键字,不管是否有错误

Optional FINALLY branches make it possible to execute keywords both when there is an error and when there is not. They are thus suitable for cleaning up after a keyword execution somewhat similarly as teardowns. There can be only one FINALLY branch and it must always be last. They can be used in combination with EXCEPT and ELSE branches and having also TRY/FINALLY structure is possible:
可选的FINALLY分支可以在有错误和没有错误的情况下执行关键字。因此,它们适合在关键字执行后进行清理,有点类似于拆卸。只能有一个FINALLY分支,并且必须始终是最后一个。它们可以与EXCEPTELSE分支结合使用,也可以具有TRY/FINALLY结构:

*** Test Cases ***
TRY/EXCEPT/ELSE/FINALLY
    TRY
        Some keyword
    EXCEPT
        Log    Error occurred!
    ELSE
        Log    No error occurred.
    FINALLY
        Log    Always executed.
    END

TRY/FINALLY
    Open Connection
    TRY
        Use Connection
    FINALLY
        Close Connection
    END

Other ways to handle errors
处理错误的其他方法

There are also other methods to execute keywords conditionally:
还有其他方法可以有条件地执行关键字:

  • The BuiltIn keyword Run Keyword And Expect Error executes a named keyword and expects that it fails with a specified error message. It is basically the same as using TRY/EXCEPT with a specified message. The syntax to specify the error message is also identical except that this keyword uses glob pattern matching, not exact match, by default. Using the native TRY/EXCEPT functionality is generally recommended unless there is a need to support older Robot Framework versions that do not support it.
    BuiltIn关键字Run Keyword And Expect Error执行命名关键字,并期望它失败并显示指定的错误消息。它基本上与对指定消息使用TRY/EXCEPT相同。指定错误消息的语法也是相同的,只是默认情况下,该关键字使用glob模式匹配,而不是精确匹配。通常建议使用本机TRY/EXCEPT功能,除非需要支持不支持该功能的较旧Robot Framework版本。
  • The BuiltIn keyword Run Keyword And Ignore Error executes a named keyword and returns its status as string PASS or FAIL along with possible return value or error message. It is basically the same as using TRY/EXCEPT/ELSE so that EXCEPT catches all errors. Using the native syntax is recommended unless old Robot Framework versions need to be supported.
    内置关键字Run Keyword And Ignore Error执行指定关键字,并以字符串PASSFAIL沿着形式返回其状态以及可能的返回值或错误消息。它基本上与使用TRY/EXCEPT/ELSE相同,以便EXCEPT捕获所有错误。建议使用本机语法,除非需要支持旧的Robot Framework版本。
  • The BuiltIn keyword Run Keyword And Return Status executes a named keyword and returns its status as a Boolean true or false. It is a wrapper for the aforementioned Run Keyword And Ignore Error. The native syntax is nowadays recommended instead.
    BuiltIn关键字Run Keyword And Return Status执行命名关键字并以布尔值true或false的形式返回其状态。它是上述Run关键字和Ignore Error的包装器。现在推荐使用本机语法。
  • Test teardowns and keyword teardowns can be used for cleaning up activities similarly as FINALLY branches.
    测试拆卸关键字拆卸可以用于清理活动,类似于FINALLY分支。
  • When keywords are implemented in Python based libraries, all Python's error handling features are readily available. This is the recommended approach especially if needed logic gets more complicated.
    当在基于Python的库中实现关键字时,Python的所有错误处理功能都可以随时使用。这是推荐的方法,特别是当需要的逻辑变得更加复杂时。

2.10   Advanced features 2.10高级功能

2.10.1   Handling keywords with same names
2.10.1处理同名关键字

Keywords that are used with Robot Framework are either library keywords or user keywords. The former come from standard libraries or external libraries, and the latter are either created in the same file where they are used or then imported from resource files. When many keywords are in use, it is quite common that some of them have the same name, and this section describes how to handle possible conflicts in these situations.
与Robot Framework一起使用的关键字是库关键字用户关键字。前者来自标准库外部库,后者要么在使用它们的同一文件中创建,要么从资源文件导入。当使用多个关键字时,其中一些关键字具有相同的名称是很常见的,本节介绍如何处理这些情况下可能发生的冲突。

Keyword scopes 关键字范围

When only a keyword name is used and there are several keywords with that name, Robot Framework attempts to determine which keyword has the highest priority based on its scope. The keyword's scope is determined on the basis of how the keyword in question is created:
当只使用一个关键字名称,并且有多个关键字具有该名称时,Robot Framework会尝试根据其范围确定哪个关键字具有最高优先级。关键字的作用域取决于关键字的创建方式:

  1. Created as a user keyword in the currently executed suite file. These keywords have the highest priority and they are always used, even if there are other keywords with the same name elsewhere.
    在当前执行的套件文件中作为用户关键字创建。这些关键字具有最高的优先级,并且总是使用它们,即使在其他地方存在具有相同名称的其他关键字。
  2. Created in a resource file and imported either directly or indirectly from another resource file. This is the second-highest priority.
    在资源文件中创建并直接或间接从另一个资源文件导入。这是第二优先事项。
  3. Created in an external test library. These keywords are used, if there are no user keywords with the same name. However, if there is a keyword with the same name in the standard library, a warning is displayed.
    在外部测试库中创建。如果没有同名的用户关键字,则使用这些关键字。但是,如果标准库中存在同名的关键字,则会显示警告。
  4. Created in a standard library. These keywords have the lowest priority.
    在标准库中创建。这些关键字的优先级最低。

Specifying a keyword explicitly
显式删除关键字

Scopes alone are not a sufficient solution, because there can be keywords with the same name in several libraries or resources, and thus, they provide a mechanism to use only the keyword of the highest priority. In such cases, it is possible to use the full name of the keyword, where the keyword name is prefixed with the name of the resource or library and a dot is a delimiter.
单独的作用域并不是一个足够的解决方案,因为在多个库或资源中可能存在具有相同名称的关键字,因此,它们提供了一种仅使用最高优先级的关键字的机制。在这种情况下,可以使用关键字的全名,其中关键字名称以资源或库的名称为前缀,点是一个逗号。

With library keywords, the long format means only using the format LibraryName.Keyword Name. For example, the keyword Run from the OperatingSystem library could be used as OperatingSystem.Run, even if there was another Run keyword somewhere else. If the library is in a module or package, the full module or package name must be used (for example, com.company.Library.Some Keyword). If a custom name is given to a library when importing it, the specified name must be used also in the full keyword name.
对于库关键字,长格式意味着只使用格式LibraryName. KeywordName。例如,OperatingSystem库中的关键字Run可以用作OperatingSystem.Run,即使在其他地方还有另一个Run关键字。如果库位于模块或包中,则必须使用完整的模块或包名称(例如,com.company.Library.Some Keyword)。如果在导入库时为其指定了自定义名称,则必须在完整的关键字名称中使用指定的名称。

Resource files are specified in the full keyword name, similarly as library names. The name of the resource is derived from the basename of the resource file without the file extension. For example, the keyword Example in a resource file myresources.html can be used as myresources.Example. Note that this syntax does not work, if several resource files have the same basename. In such cases, either the files or the keywords must be renamed. The full name of the keyword is case-, space- and underscore-insensitive, similarly as normal keyword names.
资源文件以完整的关键字名称指定,与库名称类似。资源的名称是从没有文件扩展名的资源文件的基本名称派生的。例如,资源文件myresources.html中的关键字Example可以用作myresources.Example。请注意,如果多个资源文件具有相同的基本语法,则此语法不起作用。在这种情况下,必须重命名文件或关键字。关键字的全名不区分大小写、空格和下划线,与普通关键字名称类似。

Specifying explicit priority between libraries and resources
明确图书馆和资源之间的优先级

If there are multiple conflicts between keywords, specifying all the keywords in the long format can be quite a lot work. Using the long format also makes it impossible to create dynamic test cases or user keywords that work differently depending on which libraries or resources are available. A solution to both of these problems is specifying the keyword priorities explicitly using the keyword Set Library Search Order from the BuiltIn library.
如果关键字之间存在多个冲突,那么在长格式中指定所有关键字可能会有很多工作要做。使用长格式还使得不可能创建动态测试用例或用户关键字,这些测试用例或用户关键字根据可用的库或资源而不同地工作。这两个问题的解决方案是使用BuiltIn库中的关键字SetLibrarySearchOrder显式指定关键字优先级。

Note 注意

Although the keyword has the word library in its name, it works also with resource files. As discussed above, keywords in resources always have higher priority than keywords in libraries, though.
虽然关键字的名称中有单词library,但它也适用于资源文件。如上所述,资源中的关键字总是比库中的关键字具有更高的优先级。

The Set Library Search Order accepts an ordered list or libraries and resources as arguments. When a keyword name in the test data matches multiple keywords, the first library or resource containing the keyword is selected and that keyword implementation used. If the keyword is not found from any of the specified libraries or resources, execution fails for conflict the same way as when the search order is not set.
Set Library Search Order接受有序列表或库和资源作为参数。当测试数据中的关键字名称与多个关键字匹配时,将选择包含该关键字的第一个库或资源,并使用该关键字实现。如果在任何指定的库或资源中找不到关键字,则执行将因冲突而失败,与未设置搜索顺序时的情况相同。

For more information and examples, see the documentation of the keyword.
有关更多信息和示例,请参见关键字的文档。

2.10.2   Timeouts 2.10.2超时

Sometimes keywords may take exceptionally long time to execute or just hang endlessly. Robot Framework allows you to set timeouts both for test cases and user keywords, and if a test or keyword is not finished within the specified time, the keyword that is currently being executed is forcefully stopped.
有时关键字可能需要非常长的时间来执行或只是挂无休止。Robot Framework允许您为测试用例用户关键字设置超时,如果测试或关键字未在指定时间内完成,则当前正在执行的关键字将强制停止。

Stopping keywords in this manner may leave the library, the test environment or the system under test to an unstable state, and timeouts are recommended only when there is no safer option available. In general, libraries should be implemented so that keywords cannot hang or that they have their own timeout mechanism.
以这种方式停止关键字可能会使库、测试环境或被测系统处于不稳定状态,只有在没有更安全的选项可用时才建议超时。一般来说,库的实现应该使关键字不会挂起,或者它们有自己的超时机制。

Test case timeout 测试用例超时

The test case timeout can be set either by using the Test Timeout setting in the Setting section or the [Timeout] setting with individual test cases. Test Timeout defines a default timeout for all the test cases in that suite, whereas [Timeout] applies a timeout to a particular test case and overrides the possible default value.
测试用例超时可以通过使用设置部分中的测试超时设置或单个测试用例的[超时]设置来设置。测试用例为该套件中的所有测试用例定义了一个默认超时,而[100]将超时应用于特定的测试用例并覆盖可能的默认值。

Using an empty [Timeout] means that the test has no timeout even when Test Timeout is used. It is also possible to use explicit NONE value for this purpose. The timeout is effectively ignored also if its value is zero or negative.
使用空的[]意味着即使使用了测试超时,测试也没有超时。也可以使用显式的NONE值来实现此目的。如果超时的值为零或负值,则它也会被有效地忽略。

Regardless of where the test timeout is defined, the value given to it contains the duration of the timeout. The duration must be given in Robot Framework's time format, that is, either directly in seconds like 10 or in a format like 1 minute 30 seconds. Timeouts can also be specified as variables making it possible to give them, for example, from the command line.
无论在哪里定义测试超时,为其指定的值都包含超时的持续时间。持续时间必须以Robot Framework的时间格式给出,也就是说,可以直接以秒(如10)或以1分30秒的格式给出。超时也可以指定为变量,以便可以从命令行等方式提供超时。

If there is a timeout and it expires, the keyword that is currently running is stopped and the test case fails. Keywords executed as part of test teardown are not interrupted if a test timeout occurs, though, but the test is nevertheless marked failed. If a keyword in teardown may hang, it can be stopped by using user keyword timeouts.
如果存在超时并且超时过期,则停止当前运行的关键字,测试用例失败。如果测试超时发生,作为测试拆卸的一部分执行的关键字不会中断,但是测试仍然被标记为失败。如果一个关键字在拆卸可能挂起,它可以停止使用用户关键字超时

*** Settings ***
Test Timeout       2 minutes

*** Test Cases ***
Default timeout
    [Documentation]    Default timeout from Settings is used.
    Some Keyword    argument

Override
    [Documentation]    Override default, use 10 seconds timeout.
    [Timeout]    10
    Some Keyword    argument

Variables
    [Documentation]    It is possible to use variables too.
    [Timeout]    ${TIMEOUT}
    Some Keyword    argument

No timeout
    [Documentation]    Empty timeout means no timeout even when Test Timeout has been used.
    [Timeout]
    Some Keyword    argument

No timeout 2
    [Documentation]    Disabling timeout with NONE works too and is more explicit.
    [Timeout]    NONE
    Some Keyword    argument

User keyword timeout 用户关键字超时

Timeouts can be set for user keywords using the [Timeout] setting. The syntax is exactly the same as with test case timeout, but user keyword timeouts do not have any default value. If a user keyword timeout is specified using a variable, the value can be given also as a keyword argument.
可以使用[超时]设置为用户关键字设置超时。语法与测试用例超时完全相同,但用户关键字超时没有任何默认值。如果使用变量指定用户关键字超时,则该值也可以作为关键字参数给出。

*** Keywords ***
Hardcoded
    [Arguments]    ${arg}
    [Timeout]    1 minute 42 seconds
    Some Keyword    ${arg}

Configurable
    [Arguments]    ${arg}    ${timeout}
    [Timeout]    ${timeout}
    Some Keyword    ${arg}

Run Keyword with Timeout
    [Arguments]    ${keyword}    @{args}    &{kwargs}    ${timeout}=1 minute
    [Documentation]    Wrapper that runs another keyword with a configurable timeout.
    [Timeout]    ${timeout}
    Run Keyword    ${keyword}    @{args}    &{kwargs}

A user keyword timeout is applicable during the execution of that user keyword. If the total time of the whole keyword is longer than the timeout value, the currently executed keyword is stopped. User keyword timeouts are applicable also during a test case teardown, whereas test timeouts are not.
用户关键字超时适用于该用户关键字的执行期间。如果整个关键字的总时间大于超时值,则停止当前执行的关键字。用户关键字超时也适用于测试用例拆卸期间,而测试超时则不适用。

If both the test case and some of its keywords (or several nested keywords) have a timeout, the active timeout is the one with the least time left.
如果测试用例和它的一些关键字(或几个嵌套的关键字)都有超时,则活动超时是剩余时间最少的超时。

Note 注意

With earlier Robot Framework versions it was possible to specify a custom error message to use if a timeout expires. This functionality was deprecated in Robot Framework 3.0.1 and removed in Robot Framework 3.2.
对于早期的Robot Framework版本,可以指定在超时过期时使用的自定义错误消息。此功能在Robot Framework 3.0.1中被弃用,并在Robot Framework 3.2中被删除。

2.10.3   Parallel execution of keywords
2.10.3关键字的并行执行

When parallel execution is needed, it must be implemented in test library level so that the library executes the code on background. Typically this means that the library needs a keyword like Start Something that starts the execution and returns immediately, and another keyword like Get Results From Something that waits until the result is available and returns it. See Process library keywords Start Process and Wait For Process for an example.
当需要并行执行时,必须在测试库级别实现,以便库在后台执行代码。通常这意味着库需要一个关键字(如Start Something)来启动执行并立即返回,还需要另一个关键字(如Get Results From Something)来等待直到结果可用并返回。有关示例,请参阅Process库关键字Start ProcessWait For Process

3   Executing test cases 3执行测试用例

3.1   Basic usage 3.1基本用法

Robot Framework test cases are executed from the command line, and the end result is, by default, an output file in XML format and an HTML report and log. After the execution, output files can be combined and otherwise post-processed with the Rebot tool.
Robot Framework测试用例从命令行执行,默认情况下,最终结果是XML格式的输出文件以及HTML报告日志。执行后,可以使用Rebot工具组合输出文件或进行后处理

3.1.1   Starting test execution
3.1.1开始测试执行

Synopsis 概要

robot [options] data
python -m robot [options] data
python path/to/robot/ [options] data

Execution is normally started using the robot command created as part of installation. Alternatively it is possible to execute the installed robot module using the selected Python interpreter. This is especially convenient if Robot Framework has been installed under multiple Python versions. Finally, if you know where the installed robot directory exists, it can be executed using Python as well.
执行通常使用作为安装的一部分创建的 robot 命令启动。或者,也可以使用选定的Python解释器执行已安装的 robot 模块。如果Robot Framework已经安装在多个Python版本下,这特别方便。最后,如果你知道安装的 robot 目录在哪里,也可以使用Python执行。

Regardless of execution approach, the path (or paths) to the test data to be executed is given as an argument after the command. Additionally, different command line options can be used to alter the test execution or generated outputs in many ways.
无论执行方法如何,要执行的测试数据的路径(或多个路径)都作为命令后的参数给出。此外,不同的命令行选项可以用于以多种方式更改测试执行或生成的输出。

Specifying test data to be executed
测试数据将被执行

Robot Framework test cases are created in files and directories, and they are executed by giving the path to the file or directory in question to the selected runner script. The path can be absolute or, more commonly, relative to the directory where tests are executed from. The given file or directory creates the top-level test suite, which, by default, gets its name from the file or directory name. Different execution possibilities are illustrated in the examples below. Note that in these examples, as well as in other examples in this section, only the robot script is used, but other execution approaches could be used similarly.
Robot Framework测试用例是在文件目录中创建的,并且通过将所讨论的文件或目录的路径提供给所选的运行器脚本来执行它们。路径可以是绝对路径,更常见的是相对于执行测试的目录。给定的文件或目录创建顶级测试套件,默认情况下,该套件从文件或目录名称中获取其名称。下面的示例说明了不同的执行可能性。请注意,在这些示例以及本节中的其他示例中,仅使用 robot 脚本,但可以类似地使用其他执行方法。

robot tests.robot
robot path/to/my_tests/
robot c:\robot\tests.robot

Note 注意

When executing a directory, all files and directories starting with a dot (.) or an underscore (_) are ignored and, by default, only files with the .robot extension executed. See the Selecting files to parse section for more details.
当执行目录时,所有以点(. )或下划线(_)将被忽略,并且默认情况下仅执行扩展名为.robot的文件。有关详细信息,请参阅选择要解析的文件部分

It is also possible to give paths to several test case files or directories at once, separated with spaces. In this case, Robot Framework creates the top-level test suite automatically, and the specified files and directories become its child test suites. The name of the created test suite is got from child suite names by concatenating them together with an ampersand (&) and spaces. For example, the name of the top-level suite in the first example below is My Tests & Your Tests. These automatically created names are often quite long and complicated. In most cases, it is thus better to use the --name option for overriding it, as in the second example below:
还可以同时给出多个测试用例文件或目录的路径,并用空格分隔。在这种情况下,Robot Framework自动创建顶级测试套件,指定的文件和目录成为其子测试套件。所创建的测试套件的名称是从子套件名称中获得的,方法是将子套件名称与&和空格连接在一起。例如,下面第一个示例中的顶级套件的名称是My Tests Your Tests。这些自动创建的名称通常非常长且复杂。因此,在大多数情况下,最好使用--name选项来覆盖它,如下面的第二个示例所示:

robot my_tests.robot your_tests.robot
robot --name Example path/to/tests/pattern_*.robot

Starting from Robot Framework 6.1, it is also possible to define a test suite initialisation file for the automatically created top-level suite. The path to the init file is given similarly to the test case files:
从Robot Framework 6.1开始,还可以为自动创建的顶级套件定义测试套件初始化文件。init文件的路径与测试用例文件类似:

robot __init__.robot my_tests.robot other_tests.robot

3.1.2   Using command line options
3.1.2使用命令行选项

Robot Framework provides a number of command line options that can be used to control how test cases are executed and what outputs are generated. This section explains the option syntax, and what options actually exist. How they can be used is discussed elsewhere in this chapter.
Robot Framework提供了许多命令行选项,可用于控制如何执行测试用例以及生成哪些输出。本节解释选项语法以及实际存在的选项。如何使用它们将在本章其他地方讨论。

Using options 使用选项

When options are used, they must always be given between the runner script and the data sources. For example:
当使用选项时,必须始终在运行器脚本和数据源之间提供这些选项。举例来说:

robot -L debug my_tests.robot
robot --include smoke --variable HOST:10.0.0.42 path/to/tests/

Short and long options 短期和长期期权

Options always have a long name, such as --name, and the most frequently needed options also have a short name, such as -N. In addition to that, long options can be shortened as long as they are unique. For example, --logle DEBUG works, while --lo log.html does not, because the former matches only --loglevel, but the latter matches several options. Short and shortened options are practical when executing test cases manually, but long options are recommended in start-up scripts, because they are easier to understand.
选项总是有一个长名称,如--name,最常用的选项也有一个短名称,如-N。除此之外,长选项可以缩短,只要它们是唯一的。例如,--logle DEBUG可以工作,而--lo log.html不能,因为前者只匹配--loglevel,而后者匹配多个选项。当手动执行测试用例时,短的和缩短的选项是实用的,但是在启动脚本中建议使用长的选项,因为它们更容易理解。

The long option names are case-insensitive and hyphen-insensitive, which facilitates writing option names in an easy-to-read format. For example, --SuiteStatLevel and --suite-stat-level are equivalent to, but easier to read than, --suitestatlevel.
长选项名称不区分大小写和连字符,这有助于以易于阅读的格式编写选项名称。例如,--SuiteStatLevel--suite-stat-level等效于--suiteStatlevel,但比--suiteStatlevel更容易阅读。

Note 注意

Long options being hyphen-insensitive is new in Robot Framework 6.1.
长选项不区分连字符是Robot Framework 6.1中的新特性。

Setting option values 设置选项值

Most of the options require a value, which is given after the option name. Both short and long options accept the value separated from the option name with a space, as in --include tag or -i tag. With long options, the separator can also be the equals sign, for example --include=tag, and with short options the separator can be omitted, as in -itag.
大多数选项都需要一个值,该值在选项名称之后给出。短选项和长选项都接受与选项名称用空格分隔的值,如--include标记-i标记。对于长选项,分隔符也可以是等号,例如--include=tag,对于短选项,分隔符可以省略,如-itag

Some options can be specified several times. For example, --variable VAR1:value --variable VAR2:another sets two variables. If the options that take only one value are used several times, the value given last is effective.
某些选项可以指定多次。例如,--变量VAR 1:值--变量VAR 2:另一个设置两个变量。如果只接受一个值的选项被多次使用,则最后给出的值有效。

Disabling options accepting no values
禁用不接受值的选项

Options accepting no values can be disabled by using the same option again with no prefix added or dropped. The last option has precedence regardless of how many times options are used. For example, --dryrun --dryrun --nodryrun --nostatusrc --statusrc would not activate the dry-run mode and would return normal status rc.
不接受任何值的选项可以通过再次使用相同的选项而添加或删除前缀来禁用。最后一个选项具有优先级,而不管选项使用了多少次。例如,--dryrun --dryrun --nodryrun --nostatusrc --statusrc不会激活空运行模式,并返回正常状态rc。

Simple patterns 简单的图案

Many command line options take arguments as simple patterns. These glob-like patterns are matched according to the following rules:
许多命令行选项将参数作为简单模式。这些类球体模式根据以下规则进行匹配:

  • * matches any string, even an empty string.
    *匹配任何字符串,即使是空字符串。
  • ? matches any single character.
    ? 匹配任何单个字符。
  • [abc] matches one character in the bracket.
    [abc]匹配括号中的一个字符。
  • [!abc] matches one character not in the bracket.
    [! abc]匹配一个不在括号中的字符。
  • [a-z] matches one character from the range in the bracket.
    [a-z]匹配括号中的一个字符。
  • [!a-z] matches one character not from the range in the bracket.
    [! a-z]匹配一个不在括号中的字符。
  • Unlike with glob patterns normally, path separator characters / and \ and the newline character \n are matches by the above wildcards.
    与通常的glob模式不同,路径分隔符/\以及换行符\n由上述通配符匹配。
  • Unless noted otherwise, pattern matching is case, space, and underscore insensitive.
    除非另有说明,否则模式匹配不区分大小写、空格和下划线。

Examples: 示例如下:

--test Example*        # Matches tests with name starting 'Example'.
--test Example[1-2]    # Matches tests 'Example1' and 'Example2'.
--include f??          # Matches tests with a tag that starts with 'f' is three characters long.

All matching in above examples is case, space and underscore insensitive. For example, the second example would also match test named example 1.
以上示例中的所有匹配都不区分大小写、空格和下划线。例如,第二个示例也将匹配名为example 1的测试。

If the matched text happens to contain some of the wildcard characters and they need to be matched literally, it is possible to do that by using the [...] syntax. The pattern [*] matches the literal * character, [?] matches ?, and [[] matches [. Lone [ and ] do not need to be escaped.
如果匹配的文本碰巧包含一些字符串,并且需要按字面意思匹配,则可以使用[...] 语法.模式[*]匹配文字 * 字符[?] 火柴,且[[]匹配[。孤独[]不需要逃避。

Note 注意

Support for brackets like [abc] and [!a-z] is new in Robot Framework 3.1.
支持像[abc][!a-z]是Robot Framework 3.1中的新功能。

Tag patterns 标记模式

Most tag related options accept arguments as tag patterns. They support same wildcards as simple patterns (e.g. examp??, ex*le), but they also support AND, OR and NOT operators explained below. These operators can be used for combining two or more individual tags or patterns together.
大多数与标记相关的选项接受参数作为标记模式。它们支持与简单模式相同的通配符(例如,examp??ex*le),但它们也支持ANDORNOT运算符,下面将对此进行解释。这些操作符可以用于将两个或多个单独的标签或模式组合在一起。

AND or &
&

The whole pattern matches if all individual patterns match. AND and & are equivalent:
如果所有单个模式匹配,则整个模式匹配。AND和是等价的:

--include fooANDbar     # Matches tests containing tags 'foo' and 'bar'.
--exclude xx&yy&zz      # Matches tests containing tags 'xx', 'yy', and 'zz'.
OR

The whole pattern matches if any individual pattern matches:
如果任何单个模式匹配,则整个模式匹配:

--include fooORbar      # Matches tests containing either tag 'foo' or tag 'bar'.
--exclude xxORyyORzz    # Matches tests containing any of tags 'xx', 'yy', or 'zz'.
NOT

The whole pattern matches if the pattern on the left side matches but the one on the right side does not. If used multiple times, none of the patterns after the first NOT must not match:
如果左侧的模式匹配但右侧的模式不匹配,则整个模式匹配。如果多次使用,则第一个NOT之后的模式都必须匹配:

--include fooNOTbar     # Matches tests containing tag 'foo' but not tag 'bar'.
--exclude xxNOTyyNOTzz  # Matches tests containing tag 'xx' but not tag 'yy' or tag 'zz'.

The pattern can also start with NOT in which case the pattern matches if the pattern after NOT does not match:
模式也可以以NOT开始,在这种情况下,如果NOT之后的模式不匹配,则模式匹配:

--include NOTfoo        # Matches tests not containing tag 'foo'
--include NOTfooANDbar  # Matches tests not containing tags 'foo' and 'bar'

The above operators can also be used together. The operator precedence, from highest to lowest, is AND, OR and NOT:
上述操作符也可以一起使用。运算符的优先级从高到低依次为ANDORNOT

--include xANDyORz      # Matches tests containing either tags 'x' and 'y', or tag 'z'.
--include xORyNOTz      # Matches tests containing either tag 'x' or 'y', but not tag 'z'.
--include xNOTyANDz     # Matches tests containing tag 'x', but not tags 'y' and 'z'.

Although tag matching itself is case-insensitive, all operators are case-sensitive and must be written with upper case letters. If tags themselves happen to contain upper case AND, OR or NOT, they need to specified using lower case letters to avoid accidental operator usage:
虽然标记匹配本身是不区分大小写的,但所有运算符都是区分大小写的,并且必须使用大写字母。如果标签本身碰巧包含大写的ANDORNOT,则需要使用小写字母来指定它们,以避免意外使用操作符:

--include port          # Matches tests containing tag 'port', case-insensitively
--include PORT          # Matches tests containing tag 'P' or 'T', case-insensitively
--exclude handoverORportNOTnotification

ROBOT_OPTIONS and REBOT_OPTIONS environment variables
ROBOT_OPTIONSREBOT_OPTIONS 环境变量

Environment variables ROBOT_OPTIONS and REBOT_OPTIONS can be used to specify default options for test execution and result post-processing, respectively. The options and their values must be defined as a space separated list and they are placed in front of any explicit options on the command line. The main use case for these environment variables is setting global default values for certain options to avoid the need to repeat them every time tests are run or Rebot used.
环境变量 ROBOT_OPTIONSREBOT_OPTIONS 可分别用于指定测试执行结果后处理的默认选项。这些选项及其值必须定义为一个空格分隔的列表,并放置在命令行上任何显式选项的前面。这些环境变量的主要用例是为某些选项设置全局默认值,以避免每次运行测试或使用Rebot时都需要重复它们。

export ROBOT_OPTIONS="--outputdir results --tagdoc 'mytag:Example doc with spaces'"
robot tests.robot
export REBOT_OPTIONS="--reportbackground blue:red:yellow"
rebot --name example output.xml

3.1.3   Test results 3.1.3试验结果

Command line output 命令行输出

The most visible output from test execution is the output displayed in the command line. All executed test suites and test cases, as well as their statuses, are shown there in real time. The example below shows the output from executing a simple test suite with only two test cases:
测试执行的最明显的输出是显示在命令行中的输出。所有已执行的测试套件和测试用例,以及它们的状态,都会在那里以真实的时间显示出来。下面的示例显示了执行一个简单的测试套件的输出,其中只有两个测试用例:

==============================================================================
Example test suite
==============================================================================
First test :: Possible test documentation                             | PASS |
------------------------------------------------------------------------------
Second test                                                           | FAIL |
Error message is displayed here
==============================================================================
Example test suite                                                    | FAIL |
2 tests, 1 passed, 1 failed
==============================================================================
Output:  /path/to/output.xml
Report:  /path/to/report.html
Log:     /path/to/log.html

There is also a notification on the console whenever a top-level keyword in a test case ends. A green dot is used if a keyword passes and a red F if it fails. These markers are written to the end of line and they are overwritten by the test status when the test itself ends. Writing the markers is disabled if console output is redirected to a file.
当测试用例中的顶级关键字结束时,控制台上也会有一个通知。如果关键字通过,则使用绿色点,如果失败,则使用红色F。这些标记被写到行尾,当测试本身结束时,它们被测试状态覆盖。如果控制台输出重定向到文件,则禁止写入标记。

Generated output files 生成的输出文件

The command line output is very limited, and separate output files are normally needed for investigating the test results. As the example above shows, three output files are generated by default. The first one is in XML format and contains all the information about test execution. The second is a higher-level report and the third is a more detailed log file. These files and other possible output files are discussed in more detail in the section Different output files.
命令行输出非常有限,通常需要单独的输出文件来调查测试结果。如上面的示例所示,默认情况下生成三个输出文件。第一个是XML格式的,包含所有关于测试执行的信息。第二个是更高级别的报告,第三个是更详细的日志文件。这些文件和其他可能的输出文件将在不同的输出文件一节中详细讨论。

Return codes 返回代码

Runner scripts communicate the overall test execution status to the system running them using return codes. When the execution starts successfully and no tests fail, the return code is zero. All possible return codes are explained in the table below.
运行器脚本使用返回代码将整体测试执行状态传达给运行它们的系统。当执行成功开始并且没有测试失败时,返回代码为零。下表中解释了所有可能的返回代码。

Possible return codes 可能返回的代码
RC Explanation 解释
0 All tests passed. 所有测试均通过。
1-249 Returned number of tests failed.
返回的测试失败数。
250 250 or more failures. 250次或更多失败。
251 Help or version information printed.
已打印帮助或版本信息。
252 Invalid test data or command line options.
无效的测试数据或命令行选项。
253 Test execution stopped by user.
测试执行被用户停止。
255 Unexpected internal error.
意外的内部错误。

Return codes should always be easily available after the execution, which makes it easy to automatically determine the overall execution status. For example, in bash shell the return code is in special variable $?, and in Windows it is in %ERRORLEVEL% variable. If you use some external tool for running tests, consult its documentation for how to get the return code.
返回代码应该在执行后始终容易获得,这使得自动确定整体执行状态变得容易。例如,在bash shell中,返回代码在特殊变量$?在Windows中,它位于%VRLEVEL %变量中。如果您使用一些外部工具来运行测试,请查阅其文档以了解如何获取返回代码。

The return code can be set to 0 even if there are failures using the --NoStatusRC command line option. This might be useful, for example, in continuous integration servers where post-processing of results is needed before the overall status of test execution can be determined.
即使使用--NoStatusRC命令行选项出现故障,也可以将返回代码设置为0。这可能很有用,例如,在持续集成服务器中,在确定测试执行的整体状态之前,需要对结果进行后处理。

Note 注意

Same return codes are also used with Rebot.
Rebot也使用相同的返回代码。

Errors and warnings during execution
执行期间的错误和警告

During the test execution there can be unexpected problems like failing to import a library or a resource file or a keyword being deprecated. Depending on the severity such problems are categorized as errors or warnings and they are written into the console (using the standard error stream), shown on a separate Test Execution Errors section in log files, and also written into Robot Framework's own system log. Normally these errors and warnings are generated by Robot Framework itself, but libraries can also log errors and warnings. Example below illustrates how errors and warnings look like in the log file.
在测试执行过程中,可能会出现意想不到的问题,例如无法导入库或资源文件,或者关键字被用。根据严重程度,这些问题被归类为错误或警告,并将其写入控制台(使用标准错误流),显示在日志文件中的单独测试执行错误部分,并写入Robot Framework自己的系统日志。通常这些错误和警告是由Robot Framework本身生成的,但是库也可以记录错误和警告。下面的示例说明了日志文件中的错误和警告。

20090322 19:58:42.528 ERROR Error in file '/home/robot/tests.robot' in table 'Setting' in element on row 2: Resource file 'resource.robot' does not exist
第2行元素中的表“设置"中的文件”/home/robot/tests.robot“中出错:资源文件”resource.robot“不存在
20090322 19:58:43.931 WARN Keyword 'SomeLibrary.Example Keyword' is deprecated. Use keyword `Other Keyword` instead.
不推荐使用关键字“SomeLibrary.Example Keyword”。使用关键字`Other Keyword`代替。

3.1.4   Argument files 3.1.4参数文件

Argument files allow placing all or some command line options and arguments into an external file where they will be read. This avoids the problems with characters that are problematic on the command line. If lot of options or arguments are needed, argument files also prevent the command that is used on the command line growing too long.
参数文件允许将所有或部分命令行选项和参数放置到外部文件中,以便读取它们。这避免了在命令行上出现的字符问题。如果需要很多选项或参数,参数文件还可以防止命令行中使用的命令过长。

Argument files are taken into use with --argumentfile (-A) option along with possible other command line options.
参数文件可以与--argumentfile(-A)选项沿着使用,也可以与其他命令行选项一起使用。

Note 注意

Unlike other long command line options, --argumentfile cannot be given in shortened format like --argumentf.
与其他长命令行选项不同,--argumentfile不能像--argumentf那样以缩短格式给出。

Argument file syntax 参数文件语法

Argument files can contain both command line options and paths to the test data, one option or data source per line. Both short and long options are supported, but the latter are recommended because they are easier to understand. Argument files can contain any characters without escaping, but spaces in the beginning and end of lines are ignored. Additionally, empty lines and lines starting with a hash mark (#) are ignored:
参数文件可以包含命令行选项和测试数据的路径,每行一个选项或数据源。支持短和长选项,但建议使用后者,因为它们更容易理解。参数文件可以包含任何字符而不进行转义,但行首和行尾的空格将被忽略。此外,空行和以哈希标记(#)开头的行将被忽略:

--doc This is an example (where "special characters" are ok!)
--metadata X:Value with spaces
--variable VAR:Hello, world!
# This is a comment
path/to/my/tests

In the above example the separator between options and their values is a single space. It is possible to use either an equal sign (=) or any number of spaces. As an example, the following three lines are identical:
在上面的例子中,选项和它们的值之间的分隔符是一个空格。可以使用等号(=)或任意数量的空格。例如,以下三行是相同的:

--name An Example
--name=An Example
--name       An Example

If argument files contain non-ASCII characters, they must be saved using UTF-8 encoding.
如果参数文件包含非ASCII字符,则必须使用UTF-8编码保存它们。

Using argument files 使用参数文件

Argument files can be used either alone so that they contain all the options and paths to the test data, or along with other options and paths. When an argument file is used with other arguments, its contents are placed into the original list of arguments to the same place where the argument file option was. This means that options in argument files can override options before it, and its options can be overridden by options after it. It is possible to use --argumentfile option multiple times or even recursively:
参数文件既可以单独使用,这样它们就包含了测试数据的所有选项和路径,也可以沿着其他选项和路径。当一个参数文件与其他参数一起使用时,它的内容被放置到原始参数列表中与参数文件选项相同的位置。这意味着参数文件中的选项可以覆盖它之前的选项,它的选项可以被它之后的选项覆盖。可以多次甚至递归地使用--argumentfile选项:

robot --argumentfile all_arguments.robot
robot --name Example --argumentfile other_options_and_paths.robot
robot --argumentfile default_options.txt --name Example my_tests.robot
robot -A first.txt -A second.txt -A third.txt tests.robot

Reading argument files from standard input
从标准输入阅读参数文件

Special argument file name STDIN can be used to read arguments from the standard input stream instead of a file. This can be useful when generating arguments with a script:
特殊参数文件名STDIN可用于从标准输入流而不是文件中读取参数。这在使用脚本生成参数时很有用:

generate_arguments.sh | robot --argumentfile STDIN
generate_arguments.sh | robot --name Example --argumentfile STDIN tests.robot

3.1.5   Getting help and version information
3.1.5获取帮助和版本信息

Both when executing test cases and when post-processing outputs, it is possible to get command line help with the option --help (-h). These help texts have a short general overview and briefly explain the available command line options.
在执行测试用例和后处理输出时,都可以通过选项--help(-h)获得命令行帮助。这些帮助文本有一个简短的概述,并简要说明了可用的命令行选项。

All runner scripts also support getting the version information with the option --version. This information also contains Python version and the platform type:
所有运行器脚本还支持使用选项--version获取版本信息。此信息还包含Python版本和平台类型:

$ robot --version
Robot Framework 7.0 (Python 3.12.1 on darwin)

C:\>rebot --version
Rebot 6.1.1 (Python 3.11.0 on win32)

3.1.6   Creating start-up scripts
3.1.6创建启动脚本

Test cases are often executed automatically by a continuous integration system or some other mechanism. In such cases, there is a need to have a script for starting the test execution, and possibly also for post-processing outputs somehow. Similar scripts are also useful when running tests manually, especially if a large number of command line options are needed or setting up the test environment is complicated.
测试用例通常由持续集成系统或其他机制自动执行。在这种情况下,需要有一个脚本来启动测试执行,也可能用于后处理输出。当手动运行测试时,类似的脚本也很有用,特别是当需要大量命令行选项或设置测试环境很复杂时。

In UNIX-like environments, shell scripts provide a simple but powerful mechanism for creating custom start-up scripts. Windows batch files can also be used, but they are more limited and often also more complicated. A platform-independent alternative is using Python or some other high-level programming language. Regardless of the language, it is recommended that long option names are used, because they are easier to understand than the short names.
在类UNIX环境中,shell脚本提供了一种简单但功能强大的机制来创建自定义启动脚本。也可以使用Windows批处理文件,但它们更受限制,通常也更复杂。一个独立于平台的替代方案是使用Python或其他高级编程语言。无论使用哪种语言,都建议使用长选项名称,因为它们比短名称更容易理解。

Shell script example Shell脚本示例

In this example, the same web tests in the login directory are executed with different browsers and the results combined afterwards using Rebot. The script also accepts command line options itself and simply forwards them to the robot command using the handy $* variable:
在这个例子中, login 目录中的相同Web测试在不同的浏览器中执行,然后使用Rebot组合结果。脚本本身也接受命令行选项,并使用方便的 $* 变量将它们转发给 robot 命令:

#!/bin/bash
robot --name Firefox --variable BROWSER:Firefox --output out/fx.xml --log none --report none $* login
robot --name IE --variable BROWSER:IE --output out/ie.xml --log none --report none  $* login
rebot --name Login --outputdir out --output login.xml out/fx.xml out/ie.xml

Batch file example 批处理文件示例

Implementing the above shell script example using batch files is not very complicated either. Notice that arguments to batch files can be forwarded to executed commands using %*:
使用批处理文件实现上面的shell脚本示例也不是很复杂。请注意,批处理文件的参数可以使用 %* 转发到已执行的命令:

@echo off
robot --name Firefox --variable BROWSER:Firefox --output out\fx.xml --log none --report none %* login
robot --name IE --variable BROWSER:IE --log none --output out\ie.xml --report none %* login
rebot --name Login --outputdir out --output login.xml out\fx.xml out\ie.xml

Note 注意

Prior to Robot Framework 3.1 robot and rebot commands were implemented as batch files on Windows and using them in another batch file required prefixing the whole command with call.
在Robot Framework 3.1之前, robotrebot 命令在Windows上作为批处理文件实现,在另一个批处理文件中使用它们需要在整个命令前面加上 call

Python example Python示例

When start-up scripts gets more complicated, implementing them using shell scripts or batch files is not that convenient. This is especially true if both variants are needed and same logic needs to be implemented twice. In such situations it is often better to switch to Python. It is possible to execute Robot Framework from Python using the subprocess module, but often using Robot Framework's own programmatic API is more convenient. The easiest APIs to use are robot.run_cli and robot.rebot_cli that accept same command line arguments than the robot and rebot commands.
当启动脚本变得更加复杂时,使用shell脚本或批处理文件来实现它们就不那么方便了。如果需要两种变体并且需要实现两次相同的逻辑,则尤其如此。在这种情况下,通常最好切换到Python。可以使用子进程模块从Python执行Robot Framework,但通常使用Robot Framework自己的编程API更方便。最容易使用的API是 robot.run_clirobot.rebot_cli ,它们接受与 robotrebot 命令相同的命令行参数。

The following example implements the same logic as the earlier shell script and batch file examples. In Python arguments to the script itself are available in sys.argv:
下面的示例实现与前面的shell脚本和批处理文件示例相同的逻辑。在Python中,脚本本身的参数在 sys.argv 中可用:

#!/usr/bin/env python
import sys
from robot import run_cli, rebot_cli

common = ['--log', 'none', '--report', 'none'] + sys.argv[1:] + ['login']
run_cli(['--name', 'Firefox', '--variable', 'BROWSER:Firefox', '--output', 'out/fx.xml'] + common, exit=False)
run_cli(['--name', 'IE', '--variable', 'BROWSER:IE', '--output', 'out/ie.xml'] + common, exit=False)
rebot_cli(['--name', 'Login', '--outputdir', 'out', 'out/fx.xml', 'out/ie.xml'])

Note 注意

exit=False is needed because by default run_cli exits to system with the correct return code. rebot_cli does that too, but in the above example that is fine.
需要 exit=False ,因为默认情况下 run_cli 退出到系统并返回正确的代码rebot_cli 也是这样,但在上面的例子中,这很好。

3.1.7   Making *.robot files executable
3.1.7使*.robot文件可执行

On UNIX-like operating systems it is possible to make *.robot files executable by giving them execution permission and adding a shebang like in this example:
在类UNIX操作系统上,可以通过授予执行权限并添加如下示例所示的shebang来使*.robot文件可执行:

#!/usr/bin/env robot

*** Test Cases ***
Example
    Log to console    Executing!

If the above content would be in a file example.robot and that file would be executable, it could be executed from the command line like below. Starting from Robot Framework 3.2, individually executed files can have any extension, or no extension at all, so the same would work also if the file would be named just example.
如果上面的内容将在文件example.robot中,并且该文件是可执行的,则可以像下面这样从命令行执行。从Robot Framework 3.2开始,单独执行的文件可以有任何扩展名,或者根本没有扩展名,所以如果文件被命名为example,同样也可以工作。

./example.robot

This trick does not work when executing a directory but can be handy when executing a single file. It is probably more often useful when automating tasks than when automating tests.
这个技巧在执行目录时不起作用,但在执行单个文件时很方便。它在自动化任务时可能比在自动化测试时更有用。

3.1.8   Debugging problems 3.1.8解决问题

A test case can fail because the system under test does not work correctly, in which case the test has found a bug, or because the test itself is buggy. The error message explaining the failure is shown on the command line output and in the report file, and sometimes the error message alone is enough to pinpoint the problem. More often that not, however, log files are needed because they have also other log messages and they show which keyword actually failed.
测试用例失败的原因可能是被测系统不能正常工作,在这种情况下,测试发现了一个bug,或者是因为测试本身有bug。解释失败的错误消息显示在命令行输出报告文件中,有时仅错误消息就足以查明问题。然而,更常见的情况是,需要日志文件,因为它们也有其他日志消息,并且它们显示哪个关键字实际上失败了。

When a failure is caused by the tested application, the error message and log messages ought to be enough to understand what caused it. If that is not the case, the test library does not provide enough information and needs to be enhanced. In this situation running the same test manually, if possible, may also reveal more information about the issue.
当故障是由被测应用程序引起时,错误消息和日志消息应该足以理解故障的原因。如果不是这样,则测试库没有提供足够的信息,需要增强。在这种情况下,如果可能的话,手动运行相同的测试也可能会显示有关该问题的更多信息。

Failures caused by test cases themselves or by keywords they use can sometimes be hard to debug. If the error message, for example, tells that a keyword is used with wrong number of arguments fixing the problem is obviously easy, but if a keyword is missing or fails in unexpected way finding the root cause can be harder. The first place to look for more information is the execution errors section in the log file. For example, an error about a failed test library import may well explain why a test has failed due to a missing keyword.
由测试用例本身或它们使用的关键字引起的失败有时很难调试。例如,如果错误消息指出关键字与错误数量的参数一起使用,那么解决问题显然很容易,但是如果关键字丢失或以意外的方式失败,那么找到根本原因可能会更难。查找更多信息的第一个地方是日志文件中的执行错误部分。例如,关于失败的测试库导入的错误可以很好地解释为什么由于缺少关键字而导致测试失败。

If the log file does not provide enough information by default, it is possible to execute tests with a lower log level. For example tracebacks showing where in the code the failure occurred are logged using the DEBUG level, and this information is invaluable when the problem is in an individual library keyword.
如果默认情况下日志文件没有提供足够的信息,则可以使用较低的日志级别执行测试。例如,使用DEBUG级别记录显示代码中发生故障的位置的回溯,当问题发生在单个库关键字中时,此信息非常宝贵。

Logged tracebacks do not contain information about methods inside Robot Framework itself. If you suspect an error is caused by a bug in the framework, you can enable showing internal traces by setting environment variable ROBOT_INTERNAL_TRACES to any non-empty value.
记录的追溯不包含有关Robot Framework本身内部方法的信息。如果您怀疑错误是由框架中的bug引起的,您可以通过将环境变量 ROBOT_INTERNAL_TRACES 设置为任何非空值来启用显示内部跟踪。

If the log file still does not have enough information, it is a good idea to enable the syslog and see what information it provides. It is also possible to add some keywords to the test cases to see what is going on. Especially BuiltIn keywords Log and Log Variables are useful. If nothing else works, it is always possible to search help from mailing lists or elsewhere.
如果日志文件仍然没有足够的信息,最好启用系统日志,看看它提供了什么信息。也可以在测试用例中添加一些关键字来查看发生了什么。特别是内置关键字LogLog Variables非常有用。如果没有其他的工作,它总是可以从邮件列表或其他地方搜索帮助。

Using the Python debugger (pdb)
使用Python调试器(PDB)

It is also possible to use the pdb module from the Python standard library to set a break point and interactively debug a running test. The typical way of invoking pdb by inserting:
也可以使用Python标准库中的pdb模块来设置断点并交互式地调试正在运行的测试。调用PDB的典型方式是插入:

import pdb; pdb.set_trace()

at the location you want to break into debugger will not work correctly with Robot Framework, as the standard output stream is redirected during keyword execution. Instead, you can use the following:
在您要中断调试器的位置,将无法正确使用Robot Framework,因为标准输出流在关键字执行期间被重定向。相反,您可以使用以下命令:

import sys, pdb; pdb.Pdb(stdout=sys.__stdout__).set_trace()

from within a python library or alternatively:
在Python库中,或者:

Evaluate    pdb.Pdb(stdout=sys.__stdout__).set_trace()    modules=sys, pdb

can be used directly in a test case.
可以直接用于测试用例。

3.2   Test execution 3.2测试执行

This section describes how the test suite structure created from the parsed test data is executed, how test status is determined, and how to continue executing a test case if there are failures, and how to stop the whole test execution gracefully.
本节描述如何执行从解析的测试数据创建的测试套件结构,如何确定测试状态,以及如何在出现故障时继续执行测试用例,以及如何优雅地停止整个测试执行。

3.2.1   Execution flow 3.2.1执行流程

Executed suites and tests
执行的套件和测试

Test cases are always executed within a test suite. A test suite created from a suite file has tests directly, whereas suites created from directories have child test suites which either have tests or their own child suites. By default all the tests in an executed suite are run, but it is possible to select tests using options --test, --suite, --include and --exclude. Suites containing no tests are ignored.
测试用例总是在测试套件中执行。从套件文件创建的测试套件直接包含测试,而从目录创建的套件包含子测试套件,子测试套件包含测试或它们自己的子套件。默认情况下,执行套件中的所有测试都会运行,但可以使用选项--test--suite--include--exclude选择测试。不包含测试的套件将被忽略。

The execution starts from the top-level test suite. If the suite has tests they are executed one-by-one, and if it has suites they are executed recursively in depth-first order. When an individual test case is executed, the keywords it contains are run in a sequence. Normally the execution of the current test ends if any of the keywords fails, but it is also possible to continue after failures. The exact execution order and how possible setups and teardowns affect the execution are discussed in the following sections.
执行从顶层测试套件开始。如果套件中有测试,它们会被一个接一个地执行,如果有套件,它们会以深度优先的顺序递归地执行。当一个单独的测试用例被执行时,它所包含的关键字将按顺序运行。通常,如果任何关键字失败,当前测试的执行就会结束,但也可以在失败后继续执行。确切的执行顺序以及可能的设置和拆卸如何影响执行将在以下部分中讨论。

Setups and teardowns 设置和拆卸

Setups and teardowns can be used on test suite, test case and user keyword levels.
设置和拆卸可以在测试套件测试用例用户关键字级别上使用。

Suite setup 套件设置

If a test suite has a setup, it is executed before its tests and child suites. If the suite setup passes, test execution continues normally. If it fails, all the test cases the suite and its child suites contain are marked failed. The tests and possible suite setups and teardowns in the child test suites are not executed.
如果一个测试套件有一个设置,它会在它的测试和子套件之前执行。如果套件设置通过,测试执行将正常继续。如果失败,套件及其子套件包含的所有测试用例都标记为失败。子测试套件中的测试和可能的套件设置和拆卸不会执行。

Suite setups are often used for setting up the test environment. Because tests are not run if the suite setup fails, it is easy to use suite setups for verifying that the environment is in state in which the tests can be executed.
套件设置通常用于设置测试环境。因为如果套件设置失败,测试就不会运行,所以很容易使用套件设置来验证环境是否处于可以执行测试的状态。

Suite teardown 套房拆卸

If a test suite has a teardown, it is executed after all its test cases and child suites. Suite teardowns are executed regardless of the test status and even if the matching suite setup fails. If the suite teardown fails, all tests in the suite are marked failed afterwards in reports and logs.
如果一个测试套件有一个teardown,它会在所有的测试用例和子套件之后执行。无论测试状态如何,即使匹配的套件设置失败,也会执行套件拆卸。如果套件拆卸失败,套件中的所有测试都会在报告和日志中标记为失败。

Suite teardowns are mostly used for cleaning up the test environment after the execution. To ensure that all these tasks are done, all the keywords used in the teardown are executed even if some of them fail.
套件拆卸主要用于在执行后清理测试环境。为了确保完成所有这些任务,即使其中一些失败,也会执行拆卸中使用的所有关键字

Test setup 测试设置

Possible test setup is executed before the keywords of the test case. If the setup fails, the keywords are not executed. The main use for test setups is setting up the environment for that particular test case.
在测试用例的关键字之前执行可能的测试设置。如果设置失败,则不执行关键字。测试设置的主要用途是为特定的测试用例设置环境。

Test teardown 测试拆卸

Possible test teardown is executed after the test case has been executed. It is executed regardless of the test status and also if test setup has failed.
在测试用例执行后,执行可能的测试拆卸。无论测试状态如何,如果测试设置失败,也会执行此操作。

Similarly as suite teardown, test teardowns are used mainly for cleanup activities. Also they are executed fully even if some of their keywords fail.
与套件拆卸类似,测试拆卸主要用于清理活动。即使它们的某些关键字失败,它们也会完全执行。

User keyword setup 用户关键字设置

User keyword setup is executed before the keyword body. If the setup fails, the body is not executed. There is not much difference between the keyword setup and the first keyword in the body.
用户关键字设置在关键字主体之前执行。如果设置失败,则不会执行主体。关键字设置和正文中的第一个关键字没有太大区别。

Note 注意

User keyword setups are new in Robot Framework 7.0.
用户关键字设置是Robot Framework 7.0中的新功能。

User keyword teardown 用户关键字拆卸

User keyword teardown is run after the keyword is executed otherwise, regardless the status. User keyword teardowns are executed fully even if some of their keywords would fail.
用户关键字teardown在关键字执行后运行,否则,无论状态如何。用户关键字拆卸完全执行,即使他们的一些关键字将失败。

Execution order 执行顺序

Test cases in a test suite are executed in the same order as they are defined in the test case file. Test suites inside a higher level test suite are executed in case-insensitive alphabetical order based on the file or directory name. If multiple files and/or directories are given from the command line, they are executed in the order they are given.
测试套件中的测试用例的执行顺序与测试用例文件中定义的顺序相同。更高级别测试套件中的测试套件根据文件或目录名以不区分大小写的字母顺序执行。如果从命令行给出多个文件和/或目录,则它们将按照给定的顺序执行。

If there is a need to use certain test suite execution order inside a directory, it is possible to add prefixes like 01 and 02 into file and directory names. Such prefixes are not included in the generated test suite name if they are separated from the base name of the suite with two underscores:
如果需要在目录中使用特定的测试套件执行顺序,可以在文件名和目录名中添加前缀,如0102。如果这些前缀与套件的基本名称之间用两个下划线分隔,则它们不会包含在生成的测试套件名称中:

01__my_suite.robot -> My Suite
02__another_suite.robot -> Another Suite

If the alphabetical ordering of test suites inside suites is problematic, a good workaround is giving them separately in the required order. This easily leads to overly long start-up commands, but argument files allow listing files nicely one file per line.
如果测试套件内部的字母顺序有问题,一个好的解决方法是按照所需的顺序分别给出它们。这很容易导致过长的启动命令,但参数文件允许每行列出一个文件。

It is also possible to randomize the execution order using the --randomize option.
也可以使用--randomize选项随机化执行顺序

3.2.2   Test and suite statuses
3.2.2测试和套件状态

This section explains how tests can get PASS, FAIL or SKIP status and how the suite status is determined based on test statuses.
本节解释测试如何获得PASSFAILSKIP状态,以及如何根据测试状态确定套件状态

Note 注意

The SKIP status is new in Robot Framework 4.0.
跳过状态是Robot Framework 4.0中的新功能。

PASS 通过

A test gets the PASS status if it is executed and none of the keywords it contains fails.
如果测试被执行并且它包含的关键字都没有失败,则测试获得PASS状态。

Prematurely passing tests
预先通过测试

Normally all keywords are executed, but it is also possible to use BuiltIn keywords Pass Execution and Pass Execution If to stop execution with the PASS status and not run the remaining keywords.
通常所有关键字都会被执行,但也可以使用内置关键字Pass ExecutionPass Execution If来停止执行状态为PASS的关键字,而不运行其余的关键字。

How Pass Execution and Pass Execution If behave in different situations is explained below:
传递执行传递执行If在不同情况下的行为解释如下:

  • When used in any setup or teardown (suite, test or keyword), these keywords pass that setup or teardown. Possible teardowns of the started keywords are executed. Test execution or statuses are not affected otherwise.
    当在任何设置或拆卸(套件,测试或关键字)中使用时,这些关键字会通过该设置或拆卸。执行启动关键字的可能拆卸。测试执行或状态不受其他影响。
  • When used in a test case outside setup or teardown, the keywords pass that particular test case. Possible test and keyword teardowns are executed.
    当在setup或teardown之外的测试用例中使用时,关键字通过该特定的测试用例。执行可能的测试和关键字拆卸。
  • Possible continuable failures that occur before these keyword are used, as well as failures in teardowns executed afterwards, will fail the execution.
    在使用这些关键字之前发生的可能的可持续失败,以及之后执行的拆卸失败,将导致执行失败。
  • It is mandatory to give an explanation message why execution was interrupted, and it is also possible to modify test case tags. For more details, and usage examples, see the documentation of these keywords.
    必须给出执行中断的解释消息,也可以修改测试用例标签。有关详细信息和用法示例,请参阅这些关键字的文档

Passing execution in the middle of a test, setup or teardown should be used with care. In the worst case it leads to tests that skip all the parts that could actually uncover problems in the tested application. In cases where execution cannot continue do to external factors, it is often safer to skip the test.
在测试、安装或拆卸过程中传递执行应该小心使用。在最坏的情况下,它会导致测试跳过所有可能发现测试应用程序中问题的部分。在执行不能继续做外部因素的情况下,跳过测试通常更安全。

FAIL 失败

The most common reason for a test to get the FAIL status is that one of the keywords it contains fails. The keyword itself can fail by raising an exception or the keyword can be called incorrectly. Other reasons for failures include syntax errors and the test being empty.
测试获得FAIL状态的最常见原因是它包含的关键字之一失败。关键字本身可能因引发异常而失败,或者关键字可能被错误地调用。失败的其他原因包括语法错误和测试为空。

If a suite setup fails, tests in that suite are marked failed without running them. If a suite teardown fails, tests are marked failed retroactively.
如果套件安装失败,则该套件中的测试将被标记为失败,而不运行它们。如果套件拆卸失败,测试将被追溯标记为失败。

Migrating from criticality to SKIP
从临界状态迁移到SKIP

Earlier Robot Framework versions supported criticality concept that allowed marking tests critical or non-critical. By default all tests were critical, but the --critical and --noncritical options could be used to configure that. The difference between critical and non-critical tests was that non-critical tests were not included when determining the final status for an executed test suite or for the whole test run. In practice the test status was two dimensional having PASS and FAIL in one axis and criticality on the other.
早期的Robot Framework版本支持关键性概念,允许将测试标记为关键或非关键。默认情况下,所有测试都是关键的,但可以使用--critical--noncritical选项来配置它。关键测试和非关键测试之间的区别在于,在确定已执行测试套件或整个测试运行的最终状态时,不包括非关键测试。在实践中,测试状态是二维的,一个轴上有通过和未通过,另一个轴上有关键性。

Non-critical failed tests were in many ways similar to the current skipped tests. Because these features are similar and having both SKIP and criticality would have created strange test statuses like non-critical SKIP, the criticality concept was removed in Robot Framework 4.0 when the SKIP status was introduced. The problems with criticality are explained in more detail in the issue that proposed removing it.
非关键的失败测试在许多方面与当前跳过的测试相似。由于这些功能是相似的,并且同时具有SKIP和关键性会创建奇怪的测试状态,例如非关键SKIP,因此在引入SKIP状态时,Robot Framework 4.0中删除了关键性概念。关键性的问题在建议删除它的问题中有更详细的解释。

The main use case for the criticality concept was being able to run tests that are not yet ready or that are testing a functionality that is not yet ready. This use case is nowadays covered by the skip-on-failure functionality discussed in the previous section.
关键性概念的主要用例是能够运行尚未准备好的测试或正在测试尚未准备好的功能。这个用例现在由上一节中讨论的故障时跳过功能所涵盖。

To ease migrating from criticality to skipping, the old --noncritical option worked as an alias for the new --skiponfailure in Robot Framework 4.0 and also the old --critical option was preserved. Both old options were deprecated and they were removed in Robot Framework 5.0.
为了简化从关键性到跳过的迁移,旧的--noncritical选项在Robot Framework 4.0中用作新的--skiponfailure的别名,旧的--critical选项也被保留。这两个旧选项都已弃用,并在Robot Framework 5.0中删除。

Suite status 套房状态

Suite status is determined solely based on statuses of the tests it contains:
套件状态仅根据其包含的测试的状态确定:

  • If any test has failed, suite status is FAIL.
    如果任何测试失败,套件状态为FAIL。
  • If there are no failures but at least one test has passed, suite status is PASS.
    如果没有失败,但至少有一个测试通过,则套件状态为通过。
  • If all tests have been skipped or the are no tests at all, suite status is SKIP.
    如果已跳过所有测试或根本没有测试,则套件状态为SKIP。

3.2.3   Continuing on failure
3.2.3继续失败

Normally test cases are stopped immediately when any of their keywords fail. This behavior shortens test execution time and prevents subsequent keywords hanging or otherwise causing problems if the system under test is in unstable state. This has a drawback that often subsequent keywords would give more information about the state of the system, though, and in some cases those subsequent keywords would actually take care of the needed cleanup activities. Hence Robot Framework offers several features to continue even if there are failures.
通常情况下,当任何关键字失败时,测试用例会立即停止。此行为缩短了测试执行时间,并防止后续关键字挂起或在被测系统处于不稳定状态时导致问题。这有一个缺点,通常后续的关键字会提供更多关于系统状态的信息,但是,在某些情况下,这些后续的关键字实际上会负责所需的清理活动。因此,Robot Framework提供了几个功能,即使出现故障也可以继续。

Execution continues on teardowns automatically
自动在拆卸时继续执行

To make it sure that all the cleanup activities are taken care of, the continue-on-failure mode is automatically enabled in suite, test and keyword teardowns. In practice this means that in teardowns all the keywords in all levels are always executed.
为了确保所有的清理活动都得到了处理,在套件、测试和关键字拆卸中自动启用了故障时继续模式。在实践中,这意味着在拆卸中,所有级别中的所有关键字都将被执行。

If this behavior is not desired, the special robot:stop-on-failure and robot:recursive-stop-on-failure tags can be used to disable it.
如果不需要这种行为,可以使用特殊的robot:stop-on-failurerobot:recursive-stop-on-failure标记来禁用它

All top-level keywords are executed when tests have templates
当测试有模板时,所有顶级关键字都被执行

When using test templates, all the top-level keywords are executed to make it sure that all the different combinations are covered. In this usage continuing is limited to the top-level keywords, and inside them the execution ends normally if there are non-continuable failures.
使用测试模板时,将执行所有顶级关键字,以确保涵盖所有不同的组合。在这种用法中,继续仅限于顶级关键字,如果有不可继续的失败,则在它们内部执行正常结束。

*** Test Cases ***
Continue with templates
    [Template]    Should be Equal
    this    fails
    this    is run

If this behavior is not desired, the special robot:stop-on-failure and robot:recursive-stop-on-failure tags can be used to disable it.
如果不需要此行为,则可以使用特殊的robot:stop-on-failurerobot:recursive-stop-on-failure标记来禁用它

Special failures from keywords
关键字的特殊故障

Library keywords report failures using exceptions, and it is possible to use special exceptions to tell Robot Framework that execution can continue regardless the failure. How these exceptions can be created is explained in the Continuable failures section in the Creating test libraries section.
库关键字使用异常报告失败,并且可以使用特殊异常来告诉Robot Framework无论失败如何都可以继续执行。如何创建这些异常在创建测试库部分的可持续故障部分中进行了解释。

When a test ends and there have been continuable failures, the test will be marked failed. If there are more than one failure, all of them will be enumerated in the final error message:
当测试结束并且存在可持续的失败时,测试将被标记为失败。如果有多个失败,则所有失败都将在最终错误消息中枚举:

Several failures occurred:

1) First error message.

2) Second error message.

Test execution ends also if a normal failure occurs after a continuable failure. Also in that case all the failures will be listed in the final error message.
如果在可持续故障之后发生正常故障,测试执行也会结束。在这种情况下,所有故障也将在最终错误消息中列出。

The return value from failed keywords, possibly assigned to a variable, is always the Python None.
失败的关键字的返回值,可能分配给一个变量,总是PythonNone

Run Keyword And Continue On Failure keyword
运行关键字并在失败时继续关键字

BuiltIn keyword Run Keyword And Continue On Failure allows converting any failure into a continuable failure. These failures are handled by the framework exactly the same way as continuable failures originating from library keywords discussed above.
内置关键字Run Keyword And Continue On Failure允许将任何失败转换为可持续的失败。框架处理这些故障的方式与上面讨论的库关键字引起的可持续故障完全相同。

*** Test Cases ***
Example
    Run Keyword and Continue on Failure    Should be Equal    1    2
    Log    This is executed but test fails in the end

Enabling continue-on-failure using tags
使用标记启用故障时继续

All keywords executed as part of test cases or user keywords which are tagged with the robot:continue-on-failure tag are considered continuable by default. For example, the following two tests behave identically:
作为测试用例的一部分执行的所有关键字或标记有robot:continue-on-failure标记的用户关键字默认情况下被视为可继续。例如,以下两个测试的行为相同:

*** Test Cases ***
Test 1
    Run Keyword and Continue on Failure    Should be Equal    1    2
    User Keyword 1

Test 2
    [Tags]    robot:continue-on-failure
    Should be Equal    1    2
    User Keyword 2

*** Keywords ***
User Keyword 1
    Run Keyword and Continue on Failure    Should be Equal    3    4
    Log    This is executed

User Keyword 2
    [Tags]    robot:continue-on-failure
    Should be Equal    3    4
    Log    This is executed

These tags also affect the continue-on-failure mode with different control structures. For example, the below test case will execute the Do Something keyword ten times regardless does it succeed or not:
这些标签也会影响不同控制结构的故障后继续模式。例如,下面的测试用例将执行Do Something关键字十次,无论它是否成功:

*** Test Cases ***
Example
    [Tags]    robot:continue-on-failure
    FOR    ${index}    IN RANGE    10
        Do Something
    END

Setting robot:continue-on-failure within a test case or a user keyword will not propagate the continue-on-failure behavior into user keywords they call. If such recursive behavior is needed, the robot:recursive-continue-on-failure tag can be used. For example, all keywords in the following example are executed:
设置robot:测试用例或用户关键字中的失败时继续不会将失败时继续行为传播到它们调用的用户关键字中。如果需要这种递归行为,可以使用robot:recursive-continue-on-failure标记。例如,执行以下示例中的所有关键字:

*** Test Cases ***
Example
    [Tags]    robot:recursive-continue-on-failure
    Should be Equal    1    2
    User Keyword 1
    Log    This is executed

*** Keywords ***
User Keyword 1
    Should be Equal    3    4
    User Keyword 2
    Log    This is executed

User Keyword 2
    Should be Equal    5    6
    Log    This is executed

Setting robot:continue-on-failure or robot:recursive-continue-on-failure in a test case does NOT alter the behaviour of a failure in the keyword(s) executed as part of the [Setup]: The test case is marked as failed and no test case keywords are executed.
在测试用例中设置robot:continue-on-failurerobot:recursive-continue-on-failure不会改变作为[Setup]一部分执行的关键字中的失败行为:测试用例被标记为失败,并且不执行测试用例关键字。

Note 注意

The robot:continue-on-failure and robot:recursive-continue-on-failure tags are new in Robot Framework 4.1. They do not work properly with WHILE loops prior to Robot Framework 6.0.
robot:continue-on-failurerobot:recursive-continue-on-failure标记是Robot Framework 4.1中的新功能。在Robot Framework 6.0之前,它们不能与WHILE循环正常工作。

Disabling continue-on-failure using tags
使用标记禁用故障时继续

Special tags robot:stop-on-failure and robot:recursive-stop-on-failure can be used to disable the continue-on-failure mode if needed. They work when continue-on-failure has been enabled using tags and also with teardowns and templates:
如果需要,可以使用特殊标签robot:stop-on-failurerobot:recursive-stop-on-failure来禁用continue on-failure模式。当使用标记以及拆卸模板启用了故障时继续时,它们才有效:

*** Test Cases ***
Disable continue-in-failure set using tags
    [Tags]    robot:recursive-continue-on-failure
    Keyword
    Keyword    # This is executed

Disable continue-in-failure in teardown
    No Operation
    [Teardown]    Keyword

Disable continue-in-failure with templates
    [Tags]    robot:stop-on-failure
    [Template]    Should be Equal
    this    fails
    this    is not run

*** Keywords ***
Keyword
    [Tags]    robot:stop-on-failure
    Should be Equal    this    fails
    Should be Equal    this    is not run

The robot:stop-on-failure tag affects only test cases and user keywords where it is used and does not propagate to user keywords they call nor to their own teardowns. If recursive behavior affecting all called user keywords and teardowns is desired, the robot:recursive-stop-on-failure tag can be used instead. If there is a need, its effect can again be disabled in lower level keywords by using robot:continue-on-failure or robot:recursive-continue-on-failure tags.
robot:stop-on-failure标记只影响使用它的测试用例和用户关键字,不会传播到它们调用的用户关键字,也不会传播到它们自己的拆卸。如果需要影响所有调用的用户关键字和拆卸的递归行为,则可以使用robot:recursive-stop-on-failure标记。如果需要,可以使用robot:continue-on-failurerobot:recursive-continue-on-failure标记在较低级别的关键字中再次禁用其效果。

The robot:stop-on-failure and robot:recursive-stop-on-failure tags do not alter the behavior of continuable failures caused by library keywords or by Run Keyword And Continue On Failure. For example, both keywords in this example are run even though robot:stop-on-failure is used:
robot:stop-on-failurerobot:recursive-stop-on-failure标记不会更改由库关键字Run Keyword And Continue On Failure引起的可持续失败的行为。例如,即使使用了robot:stop-on-failure,本例中的两个关键字也会运行:

*** Test Cases ***
Example
    [Tags]    robot:stop-on-failure
    Run Keyword and Continue on Failure    Should be Equal    1    2
    Log    This is executed regardless the tag

If robot:recursive-stop-on-failure and robot:continue-on-failure are used together in the same test or keyword, execution is stopped in called keywords if there are failures, but continues in the test or keyword using these tags. If robot:recursive-continue-on-failure and robot:stop-on-failure are used together in the same test or keyword, execution is continued in called keywords if there are failures, but stopped in the test or keyword using these tags.
如果robot:recursive-stop-on-failurerobot:continue-on-failure在同一个测试或关键字中一起使用,如果有失败,则在调用的关键字中停止执行,但在测试或关键字中使用这些标记继续执行。如果robot:recursive-continue-on-failurerobot:stop-on-failure在同一个测试或关键字中一起使用,如果有失败,执行将在调用的关键字中继续,但在使用这些标记的测试或关键字中停止。

Note 注意

The robot:stop-on-failure and robot:recursive-stop-on-failure tags are new in Robot Framework 6.0.
robot:stop-on-failurerobot:recursive-stop-on-failure标记是Robot Framework 6.0中新增的。

Note 注意

Using recursive and non-recursive tags together in same test or keyword is new in Robot Framework 7.0.
在同一测试或关键字中同时使用递归和非递归标记是Robot Framework 7.0中的新功能。

TRY/EXCEPT

Robot Framework 5.0 introduced native TRY/EXCEPT syntax that can be used for handling failures:
Robot Framework 5.0引入了原生TRY/EXCEPT语法,可用于处理故障:

*** Test Cases ***
Example
    TRY
        Some Keyword
    EXCEPT    Expected error message
        Error Handler Keyword
    END

For more details see the separate TRY/EXCEPT syntax section.
有关更多详细信息,请参见单独的TRY/EXCEPT语法部分。

BuiltIn keywords 内置关键字

There are several BuiltIn keywords that can be used to execute other keywords so that execution can continue after possible failures:
有几个内置关键字可用于执行其他关键字,以便在可能失败后继续执行:

  • Run Keyword And Expect Error executes a keyword and expects it to fail with the specified error message. The aforementioned TRY/EXCEPT syntax is nowadays generally recommended instead.
    Run Keyword And Expect Error执行一个关键字,并期望它失败,并显示指定的错误消息。现在通常推荐使用前面提到的TRY/EXCEPT语法。
  • Run Keyword And Ignore Error executes a keyword and silences possible error. It returns the status along with possible keyword return value or error message. The TRY/EXCEPT syntax generally works better in this case as well.
    Run Keyword And Ignore Error运行关键字并忽略可能的错误。它返回状态沿着可能的关键字返回值或错误消息。TRY/EXCEPT语法通常在这种情况下也能更好地工作。
  • Run Keyword And Warn On Failure is a wrapper for Run Keyword And Ignore Error that automatically logs a warning if the executed keyword fails.
    Run Keyword And Warn On FailureRun Keyword And Ignore Error的包装,如果执行的关键字失败,它会自动记录一个警告。
  • Run Keyword And Return Status executes a keyword and returns Boolean True or False depending on did it pass or fail.
    Run Keyword And Return Status执行一个关键字并返回布尔值TrueFalse,具体取决于它是通过还是失败。

3.2.4   Stopping test execution gracefully
3.2.4优雅地停止测试执行

Sometimes there is a need to stop the test execution before all the tests have finished, but so that logs and reports are created. Different ways how to accomplish this are explained below. In all these cases the remaining test cases are marked failed.
有时需要在所有测试完成之前停止测试执行,但这样会创建日志和报告。下面解释如何实现这一点的不同方法。在所有这些情况下,剩余的测试用例被标记为失败。

The tests that are automatically failed get robot:exit tag and the generated report will include NOT robot:exit combined tag pattern to easily see those tests that were not skipped. Note that the test in which the exit happened does not get the robot:exit tag.
自动失败的测试会获得robot:exit标签,生成的报告将包括NOT robot:exit组合标签模式,以便轻松查看那些未跳过的测试。请注意,发生退出的测试不会获取robot:exit标记。

Note 注意

Prior to Robot Framework 3.1, the special tag was named robot-exit.
在Robot Framework 3.1之前,这个特殊的标签被命名为robot-exit

Pressing Ctrl-C
Ctrl-C

The execution is stopped when Ctrl-C is pressed in the console where the tests are running. The execution is stopped immediately, but reports and logs are still generated.
当在运行测试的控制台中按下Ctrl-C时,执行将停止。执行立即停止,但仍会生成报告和日志。

If Ctrl-C is pressed again, the execution ends immediately and reports and logs are not created.
如果再次按下Ctrl-C,执行将立即结束,并且不会创建报告和日志。

Using signals 使用信号

On UNIX-like machines it is possible to terminate test execution using signals INT and TERM. These signals can be sent from the command line using kill command, and sending signals can also be easily automated.
在类UNIX机器上,可以使用信号INTTERM终止测试执行。这些信号可以使用 kill 命令从命令行发送,并且发送信号也可以很容易地自动化。

Using keywords 使用关键字

The execution can be stopped also by the executed keywords. There is a separate Fatal Error BuiltIn keyword for this purpose, and custom keywords can use fatal exceptions when they fail.
也可以通过执行的关键字停止执行。为此,有一个单独的Fatal ErrorBuiltIn关键字,自定义关键字可以在失败时使用致命异常

Stopping when first test case fails
第一个测试用例失败时停止

If option --exitonfailure (-X) is used, test execution stops immediately if any test fails. The remaining tests are marked as failed without actually executing them.
如果使用选项--exitonfailure(-X),则如果任何测试失败,测试执行将立即停止。剩余的测试在没有实际执行的情况下被标记为失败。

Stopping on parsing or execution error
分析或执行错误时停止

Robot Framework separates failures caused by failing keywords from errors caused by, for example, invalid settings or failed test library imports. By default these errors are reported as test execution errors, but errors themselves do not fail tests or affect execution otherwise. If --exitonerror option is used, however, all such errors are considered fatal and execution stopped so that remaining tests are marked failed. With parsing errors encountered before execution even starts, this means that no tests are actually run.
Robot Framework将关键字失败导致的失败与无效设置或失败的测试库导入等导致的错误分开。默认情况下,这些错误被报告为测试执行错误,但错误本身不会使测试失败或影响执行。但是,如果使用--exitonerror选项,则所有此类错误都将被视为致命错误并停止执行,因此剩余的测试将被标记为失败。由于在执行开始之前就遇到了解析错误,这意味着实际上没有运行任何测试。

Handling teardowns 处理拆卸

By default teardowns of the tests and suites that have been started are executed even if the test execution is stopped using one of the methods above. This allows clean-up activities to be run regardless how execution ends.
默认情况下,即使使用上述方法之一停止了测试执行,也会执行已启动的测试和套件的拆卸。这使得无论执行如何结束,清理活动都可以运行。

It is also possible to skip teardowns when execution is stopped by using --skipteardownonexit option. This can be useful if, for example, clean-up tasks take a lot of time.
也可以使用--skipteardownonexit选项在执行停止时跳过teardown。例如,如果清理任务需要花费大量时间,这可能很有用。

3.3   Task execution 3.3任务执行

Robot Framework can be used also for other automation purposes than test automation, and starting from Robot Framework 3.1 it is possible to explicitly create and execute tasks. For most parts task execution and test execution work the same way, and this section explains the differences.
Robot Framework还可以用于测试自动化之外的其他自动化目的,从Robot Framework 3.1开始,可以显式创建和执行任务。对于大多数部分来说,任务执行和测试执行的工作方式是相同的,本节将解释它们的区别。

3.3.1   Generic automation mode
3.3.1通用自动化模式

When Robot Framework is used execute a file and it notices that the file has tasks, not tests, it automatically sets itself into the generic automation mode. This mode does not change the actual execution at all, but when logs and reports are created, they use term task, not test. They have, for example, headers like Task Log and Task Statistics instead of Test Log and Test Statistics.
当使用Robot Framework执行一个文件时,它注意到该文件有任务,而不是测试,它会自动将自己设置为通用自动化模式。这种模式根本不会改变实际的执行,但是在创建日志和报告时,它们使用术语task,而不是test。例如,它们有类似于Task LogTask Statistics的标题,而不是Test LogTest Statistics

The generic automation mode can also be enabled by using the --rpa option. In that case the executed files can have either tests or tasks. Alternatively --norpa can be used to force the test automation mode even if executed files contain tasks. If neither of these options are used, it is an error to execute multiple files so that some have tests and others have tasks.
通用自动化模式也可以通过使用--rpa选项启用。在这种情况下,执行的文件可以包含测试或任务。或者--norpa可以用来强制测试自动化模式,即使执行的文件包含任务。如果这两个选项都没有使用,那么执行多个文件,使得一些文件有测试,而另一些文件有任务是错误的。

The execution mode is stored in the generated output file and read by Rebot if outputs are post-processed. The mode can also be set when using Rebot if necessary.
执行模式存储在生成的输出文件中,如果输出是后处理的,则由Rebot读取。如有必要,也可以在使用Rebot时设置模式。

3.4   Post-processing outputs
3.4后处理产出

XML output files that are generated during the test execution can be post-processed afterwards by the Rebot tool, which is an integral part of Robot Framework. It is used automatically when test reports and logs are generated during the test execution, and using it separately allows creating custom reports and logs as well as combining and merging results.
在测试执行过程中生成的XML输出文件可以在之后由Rebot工具进行后处理,Rebot工具是Robot Framework的组成部分。当在测试执行过程中生成测试报告和日志时,它会自动使用,单独使用它可以创建自定义报告和日志,以及组合和合并结果。

3.4.1   Using Rebot 3.4.1使用Rebot

Synopsis 概要

rebot [options] outputs
python -m robot.rebot [options] outputs
python path/to/robot/rebot.py [options] outputs

The most common way to use Rebot is using the rebot command. Alternatively it is possible to execute the installed robot.rebot module or the robot/rebot.py file using the selected Python interpreter.
使用Rebot最常见的方法是使用 rebot 命令。或者,也可以使用选定的Python解释器执行已安装的 robot.rebot 模块或 robot/rebot.py 文件。

Specifying options and arguments
选项和参数

The basic syntax for using Rebot is exactly the same as when starting test execution and also most of the command line options are identical. The main difference is that arguments to Rebot are XML output files instead of test data files or directories.
使用Rebot的基本语法与开始执行测试时完全相同,并且大多数命令行选项也相同。主要区别在于Rebot的参数是XML输出文件,而不是测试数据文件或目录。

Return codes with Rebot 使用Rebot返回代码

Return codes from Rebot are exactly same as when running tests.
Rebot的返回代码与运行测试时完全相同。

Controlling execution mode
控制执行模式

Rebot notices have tests or tasks been run, and by default preserves the execution mode. The mode affects logs and reports so that in the former case they will use term test like Test Log and Test Statistics, and in the latter case term task like Task Log and Task Statistics.
Rebot通知已运行测试任务,并默认保留执行模式。该模式影响日志和报告,因此在前一种情况下,它们将使用术语测试,测试日志测试统计信息,而在后一种情况下,术语任务,任务日志任务统计信息

Rebot also supports using --rpa or --norpa options to set the execution mode explicitly. This is necessary if multiple output files are processed and they have conflicting modes.
Rebot还支持使用--rpa--norpa选项来显式设置执行模式。如果处理多个输出文件并且它们具有冲突的模式,则这是必要的。

3.4.2   Creating reports, logs and output files
3.4.2创建报告、日志和输出文件

You can use Rebot for creating the same reports and logs that are created automatically during the test execution. Of course, it is not sensible to create the exactly same files, but, for example, having one report with all test cases and another with only some subset of tests can be useful:
您可以使用Rebot创建在测试执行期间自动创建的相同报告和日志。当然,创建完全相同的文件是不明智的,但是,例如,让一个报告包含所有测试用例,而另一个报告只包含测试的某个子集可能是有用的:

rebot output.xml
rebot path/to/output_file.xml
rebot --include smoke --name Smoke_Tests c:\results\output.xml

Another common usage is creating only the output file when running tests (log and report generation can be disabled with --log NONE --report NONE) and generating logs and reports later. Tests can, for example, be executed on different environments, output files collected to a central place, and reports and logs created there.
另一个常见的用法是在运行测试时只创建输出文件(可以使用--log NONE --report NONE禁用日志和报告生成),然后生成日志和报告。例如,测试可以在不同的环境中执行,输出文件收集到一个中心位置,并在那里创建报告和日志。

Rebot does not create XML output files by default, but it is possible to create them by using the --output (-o) option. Log and report are created by default, but they can be disabled by using value NONE (case-insensitive) if they are not needed:
默认情况下,Rebot不创建XML输出文件,但可以使用--output(-o)选项创建它们。默认情况下会创建日志和报告,但如果不需要,可以使用值NONE(不区分大小写)将其禁用:

rebot --include smoke --output smoke.xml --log none --report none original.xml

3.4.3   Combining outputs 3.4.3合并输出

An important feature in Rebot is its ability to combine outputs from different test execution rounds. This capability allows, for example, running the same test cases on different environments and generating an overall report from all outputs. Combining outputs is extremely easy, all that needs to be done is giving several output files as arguments:
Rebot的一个重要特性是它能够联合收割机从不同的测试执行回合中组合输出。例如,该功能允许在不同的环境中运行相同的测试用例并根据所有输出生成总体报告。组合输出非常容易,所需要做的就是给出几个输出文件作为参数:

rebot output1.xml output2.xml
rebot outputs/*.xml

When outputs are combined, a new top-level test suite is created so that test suites in the given output files are its child suites. This works the same way when multiple test data files or directories are executed, and also in this case the name of the top-level test suite is created by joining child suite names with an ampersand (&) and spaces. These automatically generated names are not that good, and it is often a good idea to use --name to give a more meaningful name:
当输出被组合时,一个新的顶级测试套件被创建,这样给定输出文件中的测试套件就是它的子套件。当执行多个测试数据文件或目录时,这也以相同的方式工作,并且在这种情况下,顶层测试套件的名称通过将子套件名称与&(&)和空格连接起来而创建。这些自动生成的名称并不是那么好,使用--name来给出一个更有意义的名称通常是一个好主意:

rebot --name Browser_Compatibility firefox.xml opera.xml safari.xml ie.xml
rebot --include smoke --name Smoke_Tests c:\results\*.xml

3.4.4   Merging outputs 3.4.4合并产出

If same tests are re-executed or a single test suite executed in pieces, combining results like discussed above creates an unnecessary top-level test suite. In these cases it is typically better to merge results instead. Merging is done by using --merge (-R) option which changes the way how Rebot combines two or more output files. This option itself takes no arguments and all other command line options can be used with it normally:
如果相同的测试被重新执行,或者单个测试套件被分段执行,那么像上面讨论的那样组合结果会创建不必要的顶层测试套件。在这些情况下,通常最好合并结果。合并是通过使用--merge(-R)选项来完成的,该选项改变了Rebot合并两个或多个输出文件的方式。此选项本身不带参数,所有其他命令行选项都可以正常使用:

rebot --merge original.xml merged.xml
rebot --merge --name Example first.xml second.xml third.xml

When suites are merged, documentation, suite setup and suite teardown are got from the last merged suite. Suite metadata from all merged suites is preserved so that values in latter suites have precedence.
当套件被合并时,文档、套件设置和套件拆卸将从最后一个合并的套件中获得。所有合并套件中的套件元数据都将保留,以便后面的套件中的值具有优先级。

How merging tests works is explained in the following sections discussing the two main merge use cases.
以下讨论两个主要合并用例的部分解释了合并测试的工作原理。

Note 注意

Getting suite documentation and metadata from merged suites is new in Robot Framework 6.0.
从合并的套件中获取套件文档和元数据是Robot Framework 6.0中的新功能。

Merging re-executed tests
合并重新执行的测试

There is often a need to re-execute a subset of tests, for example, after fixing a bug in the system under test or in the tests themselves. This can be accomplished by selecting test cases by names (--test and --suite options), tags (--include and --exclude), or by previous status (--rerunfailed or --rerunfailedsuites).
通常需要重新执行测试的一个子集,例如,在修复了被测系统或测试本身中的bug之后。这可以通过按名称(--test--suite选项)、标记(--include--exclude)或按以前的状态(--rerunfailed--rerunfailedsuites选择测试用例来完成。

Combining re-execution results with the original results using the default combining outputs approach does not work too well. The main problem is that you get separate test suites and possibly already fixed failures are also shown. In this situation it is better to use --merge (-R) option to tell Rebot to merge the results instead. In practice this means that tests from the latter test runs replace tests in the original. An exception to this rule is that skipped tests in latter runs are ignored and original tests preserved.
使用默认的组合输出方法将重新执行的结果与原始结果组合在一起,效果不太好。主要的问题是,您得到了单独的测试套件,并且可能已经修复的故障也会显示出来。在这种情况下,最好使用--merge(-R)选项来告诉Rebot合并结果。在实践中,这意味着来自后一个测试运行的测试将替换原始测试运行中的测试。此规则的一个例外是忽略后面运行中跳过的测试,并保留原始测试。

This usage is best illustrated by a practical example using --rerunfailed and --merge together:
这个用法可以通过一个使用--rerunfailed--merge的实际例子来最好地说明:

robot --output original.xml tests                          # first execute all tests
robot --rerunfailed original.xml --output rerun.xml tests  # then re-execute failing
rebot --merge original.xml rerun.xml                       # finally merge results

The message of the merged tests contains a note that results have been replaced. The message also shows the old status and message of the test.
合并测试的消息包含结果已被替换的注释。消息还显示测试的旧状态和消息。

Merged results must always have same top-level test suite. Tests and suites in merged outputs that are not found from the original output are added into the resulting output. How this works in practice is discussed in the next section.
合并的结果必须始终具有相同的顶级测试套件。合并输出中未在原始输出中找到的测试和套件将添加到结果输出中。下一节将讨论这在实践中是如何工作的。

Note 注意

Ignoring skipped tests in latter runs is new in Robot Framework 4.1.
在后面的运行中忽略跳过的测试是Robot Framework 4.1中的新功能。

Merging suites executed in pieces
合并套件执行在件

Another important use case for the --merge option is merging results got when running a test suite in pieces using, for example, --include and --exclude options:
--merge选项的另一个重要用例是使用--include和--exclude选项合并在运行测试套件时获得的结果:

robot --include smoke --output smoke.xml tests   # first run some tests
robot --exclude smoke --output others.xml tests  # then run others
rebot --merge smoke.xml others.xml               # finally merge results

When merging outputs like this, the resulting output contains all tests and suites found from all given output files. If some test is found from multiple outputs, latest results replace the earlier ones like explained in the previous section. Also this merging strategy requires the top-level test suites to be same in all outputs.
当像这样合并输出时,结果输出包含从所有给定输出文件中找到的所有测试和套件。如果从多个输出中找到某个测试,则最新的结果将替换先前的结果,如前一节所述。而且,这种合并策略要求顶层测试套件在所有输出中都是相同的。

3.4.5   JSON output files 3.4.5 JSON输出文件

Rebot can create and process output files also in the JSON format. Creating JSON output files is done using the normal --output option so that the specified file has a .json extension:
Rebot也可以创建和处理JSON格式的输出文件。创建JSON输出文件是使用普通的--output选项完成的,这样指定的文件就有一个.json扩展名:

rebot --output output.json output.xml

When reading output files, JSON files are automatically recognized by the extension:
当阅读输出文件时,JSON文件会被扩展名自动识别:

rebot output.json
rebot output1.json output2.json

When combining or merging results, it is possible to mix JSON and XML files:
在合并结果时,可以混合使用JSON和XML文件:

rebot output1.xml output2.json
rebot --merge original.xml rerun.json

The JSON output file structure is documented in the result.json schema file.
JSON输出文件结构记录在result.json模式文件中。

Note 注意

Support for JSON output files is new in Robot Framework 7.0.
对JSON输出文件的支持是Robot Framework 7.0中的新功能。

3.5   Configuring execution
3.5配置执行

This section explains different command line options that can be used for configuring the test execution or post-processing outputs. Options related to generated output files are discussed in the next section.
本节解释了可以用于配置测试执行后处理输出的不同命令行选项。与生成的输出文件相关的选项将在下一节中讨论。

3.5.1   Selecting files to parse
3.5.1选择要解析的文件

Executing individual files
执行单个文件

When executing individual files, Robot Framework tries to parse and run them regardless the name or the file extension. What parser to use depends on the extension:
当执行单个文件时,Robot Framework会尝试解析和运行它们,而不管文件名或文件扩展名如何。使用什么解析器取决于扩展名:

Examples: 示例如下:

robot example.robot    # Standard Robot Framework parser.
robot example.tsv      # Must be compatible with the standard parser.
robot example.rst      # reStructuredText parser.
robot x.robot y.rst    # Parse both files using an appropriate parser.

Included and excluded files
包括和排除的文件

When executing a directory, files and directories are parsed using the following rules:
执行目录时,文件和目录将使用以下规则进行解析:

  • All files and directories starting with a dot (.) or an underscore (_) are ignored.
    所有以点(开头的文件和目录)或下划线(_)将被忽略。
  • .robot files are parsed using the normal Robot Framework parser.
    .robot文件使用普通的Robot Framework解析器进行解析。
  • .robot.rst files are parsed using the reStructuredText parser.
    .robot.rst文件使用reStructuredText解析器进行解析。
  • .rbt files are parsed using the JSON parser.
    .rbt文件使用JSON解析器进行解析。
  • Files supported by custom parsers are parsed by a matching parser.
    自定义分析器支持的文件由匹配的分析器进行分析。
  • Other files are ignored unless parsing them has been enabled by using the --parseinclude or --extension options discussed in the subsequent sections.
    其他文件将被忽略,除非使用后续部分中讨论的--parseinclude--extension选项启用了对它们的解析。

Selecting files by name or path
按名称或路径选择文件

When executing a directory, it is possible to parse only certain files based on their name or path by using the --parseinclude (-I) option. This option has slightly different semantics depending on the value it is used with:
执行目录时,可以使用--parseinclude(-I)选项根据文件名或路径仅解析某些文件。此选项的语义略有不同,具体取决于与它一起使用的值:

  • If the value is just a file name like example.robot, files matching the name in all directories will be parsed.
    如果该值只是一个文件名,如example.robot,则将解析所有目录中与该名称匹配的文件。
  • To match only a certain file in a certain directory, files can be given as relative or absolute paths like path/to/tests.robot.
    为了只匹配某个目录中的某个文件,文件可以作为相对或绝对路径给出,如path/to/tests.robot
  • If the value is a path to a directory, all files inside that directory are parsed, recursively.
    如果该值是一个目录的路径,则会递归地解析该目录中的所有文件。

Examples: 示例如下:

robot --parseinclude example.robot tests       # Parse `example.robot` files anywhere under `tests`.
robot -I example_*.robot -I ???.robot tests    # Parse files matching `example_*.robot` or `???.robot` under `tests`.
robot -I tests/example.robot tests             # Parse only `tests/example.robot`.
robot --parseinclude tests/example tests       # Parse files under `tests/example` directory, recursively.

Values used with --parseinclude are case-insensitive and support glob patterns like example_*.robot. There are, however, two small differences compared to how patterns typically work with Robot Framework:
--parseinclude一起使用的值是不区分大小写的,并支持glob模式,如example_*.robot。然而,与模式通常与Robot Framework的工作方式相比,有两个小的区别:

  • * matches only a single path segment. For example, path/*/tests.robot matches path/to/tests.robot but not path/to/nested/tests.robot.
    *仅匹配单个路径段。例如,path/*/tests.robot匹配path/to/tests.robot,但不匹配path/to/nested/tests.robot
  • ** can be used to enable recursive matching. For example, path/**/tests.robot matches both path/to/tests.robot and path/to/nested/tests.robot.
    **可用于启用递归匹配。例如路径/** /tests.robot匹配path/to/tests.robotpath/to/nested/tests.robot

If the pattern contains an extension, files with that extension are parsed even if they by default would not be. What parser to use depends on the used extension:
如果模式包含扩展名,则会解析具有该扩展名的文件,即使默认情况下不会解析这些文件。使用什么解析器取决于使用的扩展名:

Notice that when you use a pattern like *.robot and there exists a file that matches the pattern in the execution directory, the shell may resolve the pattern before Robot Framework is called and the value passed to it is the file name, not the original pattern. In such cases you need to quote or escape the pattern like '*.robot' or \*.robot.
请注意,当您使用像*.robot这样的模式,并且执行目录中存在与该模式匹配的文件时,shell可能会在调用Robot Framework之前解析该模式,并且传递给它的值是文件名,而不是原始模式。在这种情况下,您需要引用或转义模式,如'*.robot'\*.robot

Note 注意

--parseinclude is new in Robot Framework 6.1.
--parseinclude是Robot Framework 6.1中的新功能。

Selecting files by extension
按扩展名选择文件

In addition to using the --parseinclude option discussed in the previous section, it is also possible to enable parsing files that are not parsed by default by using the --extension (-F) option. Matching extensions is case insensitive and the leading dot can be omitted. If there is a need to parse more than one kind of files, it is possible to use a colon : to separate extensions:
除了使用上一节中讨论的--parseinclude选项之外,还可以使用--extension(-F)选项来启用解析默认情况下不解析的文件。匹配扩展名不区分大小写,前导点可以省略。如果需要解析多种文件,可以使用冒号来分隔扩展名:

robot --extension rst path/to/tests    # Parse only *.rst files.
robot -F robot:rst path/to/tests       # Parse *.robot and *.rst files.

The above is equivalent to the following --parseinclude usage:
上面的用法相当于下面的--parseinclude用法:

robot --parseinclude *.rst path/to/tests
robot -I *.robot -I *.rst path/to/tests

Because the --parseinclude option is more powerful and covers all same use cases as the --extension option, the latter is likely to be deprecated in the future. Users are recommended to use --parseinclude already now.
因为--parseinclude选项更强大,并且覆盖了与--extension选项相同的所有用例,所以后者可能在将来被弃用。建议用户现在就使用--parseinclude

Using custom parsers 使用自定义解析器

External parsers can parse files that Robot Framework does not recognize otherwise. For more information about creating and using such parsers see the Parser interface section.
外部解析器可以解析Robot Framework无法识别的文件。有关创建和使用此类解析器的更多信息,请参见解析器接口一节。

3.5.2   Selecting test cases
3.5.2选择测试用例

Robot Framework offers several command line options for selecting which test cases to execute. The same options work also when executing tasks and when post-processing outputs with Rebot.
Robot Framework提供了几个命令行选项,用于选择要执行的测试用例。同样的选项也适用于执行任务和使用Rebot后处理输出时。

By test names 按测试名称

The easiest way to select only some tests to be run is using the --test (-t) option. As the name implies, it can be used for selecting tests by their names. Given names are case, space and underscore insensitive and they also support simple patterns. The option can be used multiple times to match multiple tests:
只选择要运行的某些测试的最简单方法是使用--test(-t)选项。顾名思义,它可以用于根据名称选择测试。给定的名称不区分大小写、空格和下划线,它们也支持简单的模式。该选项可以多次使用以匹配多个测试:

--test Example                   # Match only tests with name 'Example'.
--test example*                  # Match tests starting with 'example'.
--test first --test second       # Match tests with name 'first' or 'second'.

To pinpoint a test more precisely, it is possible to prefix the test name with a suite name:
为了更精确地定位一个测试,可以在测试名称前面加上一个套件名称:

--test mysuite.mytest            # Match test 'mytest' in suite 'mysuite'.
--test root.sub.test             # Match test 'test' in suite 'sub' in suite 'root'.
--test *.sub.test                # Match test 'test' in suite 'sub' anywhere.

Notice that when the given name includes a suite name, it must match the whole suite name starting from the root suite. Using a wildcard as in the last example above allows matching tests with a parent suite anywhere.
请注意,当给定名称包含套件名称时,它必须与从根套件开始的整个套件名称相匹配。在上面的最后一个例子中使用一个测试集允许在任何地方将测试与父套件进行匹配。

Using the --test option is convenient when only a few tests needs to be selected. A common use case is running just the test that is currently being worked on. If a bigger number of tests needs to be selected, it is typically easier to select them by suite names or by tag names.
当只需要选择几个测试时,使用--test选项很方便。一个常见的用例是只运行当前正在处理的测试。如果需要选择更多的测试,通常通过套件名称标记名称来选择它们会更容易。

When executing tasks, it is possible to use the --task option as an alias for --test.
执行任务时,可以使用--task选项作为--test的别名。

By suite names 按套房名称

Tests can be selected also by suite names with the --suite (-s) option that selects all tests in matching suites. Similarly as with --test, given names are case, space and underscore insensitive and support simple patterns. To pinpoint a suite more precisely, it is possible to prefix the name with the parent suite name:
还可以通过套件名称选择测试,使用--suite(-s)选项选择匹配套件中的所有测试。与--test类似,给定名称不区分大小写、空格和下划线,并支持简单模式。为了更精确地定位一个套件,可以使用父套件名称作为名称的前缀:

--suite Example                  # Match only suites with name 'Example'.
--suite example*                 # Match suites starting with 'example'.
--suite first --suite second     # Match suites with name 'first' or 'second'.
--suite root.child               # Match suite 'child' in root suite 'root'.
--suite *.parent.child           # Match suite 'child' with parent 'parent' anywhere.

If the name contains a parent suite name, it must match the whole suite name the same way as with --test. Using a wildcard as in the last example above allows matching suites with a parent suite anywhere.
如果名称包含父套件名称,则必须与整个套件名称匹配,方法与--test相同。在上面的最后一个例子中使用一个子目录允许在任何地方将套件与父套件进行匹配。

Note 注意

Prior to Robot Framework 7.0, --suite with a parent suite did not need to match the whole suite name. For example, parent.child would match suite child with parent parent anywhere. The name must be prefixed with a wildcard if this behavior is desired nowadays.
在Robot Framework 7.0之前,带有父套件的--suite不需要匹配整个套件名称。例如,parent.child将匹配suitechild和parentparent anywhere。如果现在需要这种行为,则必须在名称前面加上前缀。

If both --suite and --test options are used, only the specified tests in specified suites are selected:
如果同时使用--suite--test选项,则仅选择指定套件中的指定测试:

--suite mysuite --test mytest    # Match test 'mytest' if its inside suite 'mysuite'.

Using the --suite option is more or less the same as executing the appropriate suite file or directory directly. The main difference is that if a file or directory is run directly, possible suite setups and teardowns on higher level are not executed:
使用--suite选项或多或少与直接执行适当的suite文件或目录相同。主要区别在于,如果直接运行文件或目录,则不会执行更高级别的可能套件设置和拆卸:

# Root suite is 'Tests' and its possible setup and teardown are run.
robot --suite example path/to/tests

# Root suite is 'Example' and possible higher level setups and teardowns are ignored.
robot path/to/tests/example.robot

Prior to Robot Framework 6.1, files not matching the --suite option were not parsed at all for performance reasons. This optimization was not possible anymore after suites got a new Name setting that can override the default suite name that is got from the file or directory name. New --parseinclude option has been added to explicitly select which files are parsed if this kind of parsing optimization is needed.
在Robot Framework 6.1之前,出于性能原因,根本不会解析与--suite选项不匹配的文件。在套件获得新的名称设置后,这种优化不再可能,该设置可以覆盖从文件或目录名称获得的默认套件名称。添加了新的--parseinclude选项,以显式选择在需要这种解析优化时解析哪些文件。

By tag names 按标签名称

It is possible to include and exclude test cases by tag names with the --include (-i) and --exclude (-e) options, respectively. If the --include option is used, only test cases having a matching tag are selected, and with the --exclude option test cases having a matching tag are not. If both are used, only tests with a tag matching the former option, and not with a tag matching the latter, are selected:
可以通过分别带有--include(-i)--exclude(-e)选项的标记名来包含和排除测试用例。如果使用--include选项,则只选择具有匹配标记的测试用例,而使用--exclude选项,则不选择具有匹配标记的测试用例。如果同时使用这两个选项,则只选择具有与前一个选项匹配的标记的测试,而不选择具有与后一个选项匹配的标记的测试:

--include example
--exclude not_ready
--include regression --exclude long_lasting

Both --include and --exclude can be used several times to match multiple tags. In that case a test is selected if it has a tag that matches any included tags, and also has no tag that matches any excluded tags.
--include--exclude都可以多次使用来匹配多个标记。在这种情况下,如果测试具有与任何包含的标签匹配的标签,并且也没有与任何排除的标签匹配的标签,则选择该测试。

In addition to specifying a tag to match fully, it is possible to use tag patterns where * and ? are wildcards and AND, OR, and NOT operators can be used for combining individual tags or patterns together:
除了指定要完全匹配的标记外,还可以使用标记模式,其中 *是通配符,ANDORNOT运算符可用于将单个标记或模式组合在一起:

--include feature-4?
--exclude bug*
--include fooANDbar
--exclude xxORyyORzz
--include fooNOTbar

Starting from RF 5.0, it is also possible to use the reserved tag robot:exclude to achieve the same effect as with using the --exclude option:
从RF 5.0开始,也可以使用保留的tagrobot:exclude来实现与使用--exclude选项相同的效果:

*** Test Cases ***
Example
   [Tags]    robot:exclude
   Fail      This is not executed

Selecting test cases by tags is a very flexible mechanism and allows many interesting possibilities:
通过标签选择测试用例是一种非常灵活的机制,并允许许多有趣的可能性:

  • A subset of tests to be executed before other tests, often called smoke tests, can be tagged with smoke and executed with --include smoke.
    在其他测试之前执行的测试子集,通常称为烟雾测试,可以用烟雾标记并使用--include smoke执行。
  • Unfinished test can be committed to version control with a tag such as not_ready and excluded from the test execution with --exclude not_ready.
    未完成的测试可以使用诸如not_ready的标记提交到版本控制,并使用--exclude not_ready从测试执行中排除。
  • Tests can be tagged with sprint-<num>, where <num> specifies the number of the current sprint, and after executing all test cases, a separate report containing only the tests for a certain sprint can be generated (for example, rebot --include sprint-42 output.xml).
    测试可以用sprint-<num>标记,其中<num>指定当前sprint的编号,在执行所有测试用例后,可以生成一个单独的报告,其中只包含某个sprint的测试(例如,rebot --include sprint-42 output.xml)。

Options --include and --exclude can be used in combination with --suite and --test discussed in the previous section. In that case tests that are selected must match all selection criteria:
选项--include--exclude可以与上一节讨论的--suite--test结合使用。在这种情况下,选择的测试必须符合所有选择标准:

--suite example --include tag    # Match test if it is in suite 'example' and has tag 'tag'.
--suite example --exclude tag    # Match test if it is in suite 'example' and does not have tag 'tag'.
--test ex* --include tag         # Match test if its name starts with 'ex' and it has tag 'tag'.
--test ex* --exclude tag         # Match test if its name starts with 'ex' and it does not have tag 'tag'.

Note 注意

In Robot Framework 7.0 --include and --test were cumulative and selected tests needed to match only either of these options. That behavior caused backwards incompatibility problems and it was changed back to the original already in Robot Framework 7.0.1.
在Robot Framework 7.0中,--include--test是累积的,所选的测试只需要匹配这两个选项中的任何一个。该行为导致向后不兼容问题,并已在Robot Framework 7.0.1中更改回原始版本。

Re-executing failed test cases
重新执行失败的测试用例

Command line option --rerunfailed (-R) can be used to select all failed tests from an earlier output file for re-execution. This option is useful, for example, if running all tests takes a lot of time and one wants to iteratively fix failing test cases.
命令行选项--rerunfailed(-R)可用于从先前的输出文件中选择所有失败的测试以重新执行。这个选项很有用,例如,如果运行所有测试需要花费很多时间,并且想要迭代地修复失败的测试用例。

robot tests                             # first execute all tests
robot --rerunfailed output.xml tests    # then re-execute failing

Behind the scenes this option selects the failed tests as they would have been selected individually using the --test option. It is possible to further fine-tune the list of selected tests by using --test, --suite, --include and --exclude options.
在幕后,该选项选择失败的测试,因为它们是使用--test选项单独选择的。可以通过使用--test--suite--include--exclude选项进一步微调所选测试的列表。

It is an error if the output contains no failed tests, but this behavior can be changed by using the --runemptysuite option discussed below. Using an output not originating from executing the same tests that are run now causes undefined results. Using a special value NONE as the output is same as not specifying this option at all.
如果输出不包含失败的测试,则会出现错误,但可以使用下面讨论的--runemptysuite选项更改此行为。如果使用的输出不是来自执行与现在运行的测试相同的测试,则会导致未定义的结果。使用特殊值NONE作为输出与根本不指定此选项相同。

Tip 尖端

Re-execution results and original results can be merged together using the --merge command line option.
可以使用--merge命令行选项将重新执行结果和原始结果合并在一起

Re-executing failed test suites
重新执行失败的测试套件

Command line option --rerunfailedsuites (-S) can be used to select all failed suites from an earlier output file for re-execution. Like --rerunfailed (-R), this option is useful when full test execution takes a lot of time. Note that all tests from a failed test suite will be re-executed, even passing ones. This option is useful when the tests in a test suite depends on each other.
命令行选项--rerunfailedsuites(-S)可用于从先前的输出文件中选择所有失败的套件以重新执行。与--rerunfailed(-R)类似,当完整的测试执行需要花费大量时间时,此选项非常有用。请注意,失败测试套件中的所有测试都将重新执行,即使是通过的测试也是如此。当测试套件中的测试相互依赖时,此选项非常有用。

Behind the scenes this option selects the failed suites as they would have been selected individually with the --suite option. It is possible to further fine-tune the list of selected tests by using --test, --suite, --include and --exclude options.
在后台,这个选项选择失败的套件,就像使用--suite选项单独选择它们一样。可以通过使用--test--suite--include--exclude选项进一步微调所选测试的列表。

When no tests match selection
当没有测试匹配选择时

By default when no tests match the selection criteria test execution fails with an error like:
默认情况下,当没有测试匹配选择标准时,测试执行失败,并出现以下错误:

[ ERROR ] Suite 'Example' contains no tests matching tag 'xxx'.

Because no outputs are generated, this behavior can be problematic if tests are executed and results processed automatically. Luckily a command line option --RunEmptySuite (case-insensitive) can be used to force the suite to be executed also in this case. As a result normal outputs are created but show zero executed tests. The same option can be used also to alter the behavior when an empty directory or a test case file containing no tests is executed.
由于不生成任何输出,因此如果执行测试并自动处理结果,则此行为可能会有问题。幸运的是,在这种情况下,可以使用命令行选项RunEmptySuite(不区分大小写)强制执行套件。因此,创建了正常输出,但显示零个已执行的测试。当执行空目录或不包含测试的测试用例文件时,也可以使用相同的选项来更改行为。

Similar situation can occur also when processing output files with Rebot. It is possible that no test match the used filtering criteria or that the output file contained no tests to begin with. By default executing Rebot fails in these cases, but it has a separate --ProcessEmptySuite option that can be used to alter the behavior. In practice this option works the same way as --RunEmptySuite when running tests.
使用Rebot处理输出文件时也可能发生类似的情况。可能没有测试与使用的过滤条件匹配,或者输出文件不包含任何可用于开始的测试。默认情况下,在这些情况下执行Rebot会失败,但它有一个单独的--ProcessEmptySuite选项可用于改变行为。实际上,在运行测试时,此选项的工作方式与--RunEmptySuite相同。

Note 注意

Using --RunEmptySuite with --ReRunFailed or --ReRunFailedSuites requires Robot Framework 5.0.1 or newer.
--RunEmptySuite--ReRunFailed--ReRunFailedSuites配合使用需要Robot Framework 5.0.1或更高版本。

3.5.3   Setting metadata 3.5.3设置元数据

Setting suite name 设置套件名称

When Robot Framework parses test data, suite names are created from file and directory names. The name of the top-level test suite can, however, be overridden with the command line option --name (-N):
当Robot Framework解析测试数据时,套件名称是从文件和目录名称创建的。但是,顶级测试套件的名称可以使用命令行选项--name(-N)覆盖:

robot --name "Custom name" tests.robot

Setting suite documentation
设置套件文档

In addition to defining documentation in the test data, documentation of the top-level suite can be given from the command line with the option --doc (-D). The value can contain simple HTML formatting and must be quoted if it contains spaces.
除了在测试数据中定义文档之外,还可以通过命令行选项--doc(-D)来提供顶级套件的文档。该值可以包含简单的HTML格式,如果包含空格,则必须用引号括起来。

If the given documentation is a relative or absolute path pointing to an existing file, the actual documentation will be read from that file. This is especially convenient if the externally specified documentation is long or contains multiple lines.
如果给定的文档是指向现有文件的相对或绝对路径,则将从该文件中读取实际文档。如果外部指定的文档很长或包含多行,这将特别方便。

Examples: 示例如下:

robot --doc "Example documentation" tests.robot
robot --doc doc.txt tests.robot    # Documentation read from doc.txt if it exits.

Note 注意

Reading documentation from an external file is new in Robot Framework 4.1.
从外部文件阅读文档是Robot Framework 4.1中的新增功能。

Prior to Robot Framework 3.1, underscores in documentation were converted to spaces same way as with the --name option.
在Robot Framework 3.1之前,文档中的下划线转换为空格的方式与--name选项相同。

Setting free suite metadata
设置免费套件元数据

Free suite metadata may also be given from the command line with the option --metadata (-M). The argument must be in the format name:value, where name the name of the metadata to set and value is its value. The value can contain simple HTML formatting and the whole argument must be quoted if it contains spaces. This option may be used several times to set multiple metadata values.
自由套件元数据也可以从命令行使用选项--metadata(-M)给出。参数的格式必须为name:value,其中name是要设置的元数据的名称,value是其值。该值可以包含简单的HTML格式,如果包含空格,则整个参数必须用引号括起来。该选项可以多次使用来设置多个元数据值。

If the given value is a relative or absolute path pointing to an existing file, the actual value will be read from that file. This is especially convenient if the value is long or contains multiple lines. If the value should be a path to an existing file, not read from that file, the value must be separated with a space from the name: part.
如果给定值是指向现有文件的相对或绝对路径,则将从该文件读取实际值。如果值很长或包含多行,这一点尤其方便。如果该值应该是现有文件的路径,而不是从该文件中读取,则该值必须与名称:部分用空格分隔。

Examples: 示例如下:

robot --metadata Name:Value tests.robot
robot --metadata "Another Name:Another value, now with spaces" tests.robot
robot --metadata "Read From File:meta.txt" tests.robot    # Value read from meta.txt if it exists.
robot --metadata "Path As Value: meta.txt" tests.robot    # Value always used as-is.

Note 注意

Reading metadata value from an external file is new in Robot Framework 4.1.
从外部文件中阅读元数据值是Robot Framework 4.1中的新增功能。

Prior to Robot Framework 3.1, underscores in the value were converted to spaces same way as with the --name option.
在Robot Framework 3.1之前,值中的下划线转换为空格的方式与--name选项相同。

Setting test tags 设置测试标签

The command line option --settag (-G) can be used to set the given tag to all executed test cases. This option may be used several times to set multiple tags.
命令行选项--setag(-G)可以用来为所有执行的测试用例设置给定的标记。此选项可以多次使用以设置多个标记。

3.5.4   Configuring where to search libraries and other extensions
3.5.4配置搜索库和其他扩展的位置

When Robot Framework imports a test library, listener, or some other Python based extension, it uses the Python interpreter to import the module containing the extension from the system. The list of locations where modules are looked for is called the module search path, and its contents can be configured using different approaches explained in this section.
当Robot Framework导入测试库监听器或其他基于Python的扩展时,它使用Python解释器从系统导入包含扩展的模块。查找模块的位置列表称为模块搜索路径,可以使用本节中介绍的不同方法配置其内容。

Robot Framework uses Python's module search path also when importing resource and variable files if the specified path does not match any file directly.
如果指定的路径不直接匹配任何文件,Robot Framework在导入资源和变量文件时也使用Python的模块搜索路径。

The module search path being set correctly so that libraries and other extensions are found is a requirement for successful test execution. If you need to customize it using approaches explained below, it is often a good idea to create a custom start-up script.
正确设置模块搜索路径以便找到库和其他扩展是成功执行测试的必要条件。如果您需要使用下面介绍的方法对其进行自定义,那么创建自定义启动脚本通常是一个好主意。

Locations automatically in module search path
模块搜索路径中的自动位置

Python interpreters have their own standard library as well as a directory where third party modules are installed automatically in the module search path. This means that test libraries packaged using Python's own packaging system are automatically installed so that they can be imported without any additional configuration.
Python解释器有自己的标准库,以及一个在模块搜索路径中自动安装第三方模块的目录。这意味着使用Python自己的打包系统打包的测试库会自动安装,因此它们可以在没有任何额外配置的情况下导入。

PYTHONPATH

Python reads additional locations to be added to the module search path from PYTHONPATH environment variables. If you want to specify more than one location in any of them, you need to separate the locations with a colon on UNIX-like machines (e.g. /opt/libs:$HOME/testlibs) and with a semicolon on Windows (e.g. D:\libs;%HOMEPATH%\testlibs).
Python从 PYTHONPATH 环境变量中读取要添加到模块搜索路径中的其他位置。如果你想在其中指定多个位置,你需要在类UNIX的机器上用冒号分隔位置(例如/opt/libs:$HOME/testlibs),在Windows上用冒号分隔位置(例如D:\libs;%HOMEPATH%\testlibs)。

Environment variables can be configured permanently system wide or so that they affect only a certain user. Alternatively they can be set temporarily before running a command, something that works extremely well in custom start-up scripts.
环境变量可以在系统范围内永久配置,或者只影响某个用户。或者,它们可以在运行命令之前临时设置,这在自定义启动脚本中非常有效。

Using --pythonpath option
使用--pythonpath选项

Robot Framework has a separate command line option --pythonpath (-P) for adding locations to the module search path.
Robot Framework有一个单独的命令行选项--pythonpath(-P),用于向模块搜索路径添加位置。

Multiple locations can be given by separating them with a colon (:) or a semicolon (;) or by using this option multiple times. If the value contains both colons and semicolons, it is split from semicolons. Paths can also be glob patterns matching multiple paths, but they typically need to be escaped when used on the console.
可以通过使用冒号()或分号(;)分隔或多次使用此选项来指定多个位置。如果该值同时包含冒号和分号,则从分号中拆分。路径也可以是匹配多个路径的glob模式,但在控制台上使用时通常需要转义。

Examples: 示例如下:

--pythonpath libs
--pythonpath /opt/testlibs:mylibs.zip:yourlibs
--pythonpath /opt/testlibs --pythonpath mylibs.zip --pythonpath yourlibs
--pythonpath c:\temp;d:\resources
--pythonpath  lib/\*.zip    # '*' is escaped

Note 注意

Both colon and semicolon work regardless the operating system. Using semicolon is new in Robot Framework 5.0.
无论操作系统如何,冒号和冒号都可以工作。使用Robot Framework 5.0中的新功能。

Configuring sys.path programmatically
编程方式配置系统路径

Python interpreters store the module search path they use as a list of strings in sys.path attribute. This list can be updated dynamically during execution, and changes are taken into account next time when something is imported.
Python解释器将它们使用的模块搜索路径作为字符串列表存储在sys.path属性中。这个列表可以在执行过程中动态更新,并且在下次导入时会考虑更改。

3.5.5   Setting variables 3.5.5设置变量

Variables can be set from the command line either individually using the --variable (-v) option or through variable files with the --variablefile (-V) option. Variables and variable files are explained in separate chapters, but the following examples illustrate how to use these options:
变量可以在命令行中单独使用--variable(-v)选项设置,也可以通过变量文件使用--variablefile(-V)选项设置。变量和变量文件在单独的章节中解释,但以下示例说明如何使用这些选项:

--variable name:value
--variable OS:Linux --variable IP:10.0.0.42
--variablefile path/to/variables.py
--variablefile myvars.py:possible:arguments:here
--variable ENVIRONMENT:Windows --variablefile c:\resources\windows.py

3.5.6   Dry run 3.5.6空运行

Robot Framework supports so called dry run mode where the tests are run normally otherwise, but the keywords coming from the test libraries are not executed at all. The dry run mode can be used to validate the test data; if the dry run passes, the data should be syntactically correct. This mode is triggered using option --dryrun.
Robot Framework支持所谓的空运行模式,在这种模式下,测试正常运行,但根本不执行来自测试库的关键字。空运行模式可用于验证测试数据;如果空运行通过,则数据在语法上应该正确。此模式使用选项--dryrun触发。

The dry run execution may fail for following reasons:
试运行执行可能会因以下原因而失败:

  • Using keywords that are not found.
    使用找不到的关键字。
  • Using keywords with wrong number of arguments.
    使用带有错误数量参数的关键字。
  • Using user keywords that have invalid syntax.
    使用语法无效的用户关键字。

In addition to these failures, normal execution errors are shown, for example, when test library or resource file imports cannot be resolved.
除了这些失败之外,还会显示正常的执行错误,例如,当无法解析测试库或资源文件导入时。

It is possible to disable dry run validation of specific user keywords by adding a special robot:no-dry-run keyword tag to them. This is useful if a keyword fails in the dry run mode for some reason, but work fine when executed normally.
可以通过添加一个特殊的robot:no-dry-runkeyword标签来禁用特定用户关键字的空运行验证。如果关键字由于某种原因在空运行模式下失败,但在正常执行时工作正常,则这很有用。

Note 注意

The dry run mode does not validate variables.
空运行模式不验证变量。

3.5.7   Randomizing execution order
3.5.7随机化执行顺序

The test execution order can be randomized using option --randomize <what>[:<seed>], where <what> is one of the following:
可以使用选项--randomize <what>[:<seed>]随机化测试执行顺序,其中<what>是下列之一:

tests
Test cases inside each test suite are executed in random order.
每个测试套件中的测试用例以随机顺序执行。
suites
All test suites are executed in a random order, but test cases inside suites are run in the order they are defined.
所有测试套件都以随机顺序执行,但套件中的测试用例按定义的顺序运行。
all
Both test cases and test suites are executed in a random order.
测试用例和测试套件都以随机顺序执行。
none
Neither execution order of test nor suites is randomized. This value can be used to override the earlier value set with --randomize.
测试和套件的执行顺序都不是随机的。这个值可以用来覆盖之前用--randomize设置的值。

It is possible to give a custom seed to initialize the random generator. This is useful if you want to re-run tests using the same order as earlier. The seed is given as part of the value for --randomize in format <what>:<seed> and it must be an integer. If no seed is given, it is generated randomly. The executed top level test suite automatically gets metadata named Randomized that tells both what was randomized and what seed was used.
可以给出自定义种子来初始化随机生成器。如果您想使用与先前相同的顺序重新运行测试,这将非常有用。种子作为--randomize的值的一部分以格式<what>:<seed>给出,并且它必须是整数。如果没有给出种子,则随机生成。执行的顶级测试套件自动获得名为Randomized的元数据,该元数据告诉什么是随机的以及使用了什么种子。

Examples: 示例如下:

robot --randomize tests my_test.robot
robot --randomize all:12345 path/to/tests

3.5.8   Programmatic modification of test data
3.5.8试验数据的程序化修改

If the provided built-in features to modify test data before execution are not enough, Robot Framework makes it possible to do custom modifications programmatically. This is accomplished by creating a so called pre-run modifier and activating it using the --prerunmodifier option.
如果提供的内置功能在执行之前修改测试数据还不够,Robot Framework可以通过编程方式进行自定义修改。这是通过创建一个所谓的pre-run修饰符并使用--prerunmodifier选项激活它来实现的。

Pre-run modifiers should be implemented as visitors that can traverse through the executable test suite structure and modify it as needed. The visitor interface is explained as part of the Robot Framework API documentation, and it possible to modify executed test suites, test cases and keywords using it. The examples below ought to give an idea of how pre-run modifiers can be used and how powerful this functionality is.
预运行修改器应该被实现为访问者,可以遍历可执行的测试套件结构,并根据需要修改它。访问者界面是Robot Framework API文档的一部分,可以使用它修改已执行的测试套件测试用例关键字。下面的示例应该可以让您了解如何使用预运行修改器以及此功能的强大程度。

When a pre-run modifier is taken into use on the command line using the --prerunmodifier option, it can be specified either as a name of the modifier class or a path to the modifier file. If the modifier is given as a class name, the module containing the class must be in the module search path, and if the module name is different than the class name, the given name must include both like module.ModifierClass. If the modifier is given as a path, the class name must be same as the file name. For most parts this works exactly like when importing a test library.
当在命令行中使用--prerunmodifier选项使用预运行修改器时,可以将其指定为修改器类的名称或修改器文件的路径。如果修饰符作为类名给出,则包含该类的模块必须在模块搜索路径中,如果模块名与类名不同,则给定的名称必须包括两者,如模块.ModifierClass。如果修饰符作为路径给出,则类名必须与文件名相同。对于大多数部分,这与导入测试库时的工作方式完全相同。

If a modifier requires arguments, like the examples below do, they can be specified after the modifier name or path using either a colon (:) or a semicolon (;) as a separator. If both are used in the value, the one used first is considered to be the actual separator. Starting from Robot Framework 4.0, arguments also support the named argument syntax as well as argument conversion based on type hints and default values the same way as keywords do.
如果一个修饰符需要参数,就像下面的例子一样,它们可以在修饰符名称或路径之后指定,使用冒号()或分号(;)作为分隔符。如果两个都在值中使用,则首先使用的一个被认为是实际的分隔符。从Robot Framework 4.0开始,参数也支持命名参数语法以及基于类型提示默认值的参数转换,与关键字相同。

If more than one pre-run modifier is needed, they can be specified by using the --prerunmodifier option multiple times. If similar modifying is needed before creating logs and reports, programmatic modification of results can be enabled using the --prerebotmodifier option.
如果需要多个预运行修饰符,可以通过多次使用--prerunmodifier选项来指定它们。如果在创建日志和报告之前需要类似的修改,可以使用--prerebotmodifier选项启用结果的编程修改

Pre-run modifiers are executed before other configuration affecting the executed test suite and test cases. Most importantly, options related to selecting test cases are processed after modifiers, making it possible to use options like --include also with possible dynamically added tests.
预运行修改器在影响已执行测试套件和测试用例的其他配置之前执行。最重要的是,与选择测试用例相关的选项在修饰符之后进行处理,这使得可以在可能的动态添加测试中使用--include这样的选项。

Tip 尖端

Modifiers are taken into use from the command line exactly the same way as listeners. See the Registering listeners from command line section for more information and examples.
从命令行使用修饰符的方式与监听器完全相同。有关更多信息和示例,请参见从命令行注册侦听器部分

Example: Select every Xth test
示例:选择每第X次测试

The first example shows how a pre-run modifier can remove tests from the executed test suite structure. In this example only every Xth tests is preserved, and the X is given from the command line along with an optional start index.
第一个例子展示了预运行修改器如何从已执行的测试套件结构中删除测试。在本例中,只保留每第X次测试,X是从命令行沿着可选的开始索引给出的。

"""Pre-run modifier that selects only every Xth test for execution.

Starts from the first test by default. Tests are selected per suite.
"""

from robot.api import SuiteVisitor


class SelectEveryXthTest(SuiteVisitor):

    def __init__(self, x: int, start: int = 0):
        self.x = x
        self.start = start

    def start_suite(self, suite):
        """Modify suite's tests to contain only every Xth."""
        suite.tests = suite.tests[self.start::self.x]

    def end_suite(self, suite):
        """Remove suites that are empty after removing tests."""
        suite.suites = [s for s in suite.suites if s.test_count > 0]

    def visit_test(self, test):
        """Avoid visiting tests and their keywords to save a little time."""
        pass

If the above pre-run modifier is in a file SelectEveryXthTest.py and the file is in the module search path, it could be used like this:
如果上述预运行修饰符位于文件SelectEveryXthTest.py中,并且该文件位于模块搜索路径中,则可以如下使用:

# Specify the modifier as a path. Run every second test.
robot --prerunmodifier path/to/SelectEveryXthTest.py:2 tests.robot

# Specify the modifier as a name. Run every third test, starting from the second.
robot --prerunmodifier SelectEveryXthTest:3:1 tests.robot

Note 注意

Argument conversion based on type hints like x: int in the above example is new in Robot Framework 4.0 and requires Python 3.
基于类型提示的参数转换,如上面示例中的x:int,是Robot Framework 4.0中的新功能,需要Python 3。

Example: Exclude tests by name
示例:按名称搜索测试

Also the second example removes tests, this time based on a given name pattern. In practice it works like a negative version of the built-in --test option.
第二个示例也删除了测试,这一次是基于给定的名称模式。实际上,它的工作方式类似于内置--test选项的否定版本。

"""Pre-run modifier that excludes tests by their name.

Tests to exclude are specified by using a pattern that is both case and space
insensitive and supports '*' (match anything) and '?' (match single character)
as wildcards.
"""

from robot.api import SuiteVisitor
from robot.utils import Matcher


class ExcludeTests(SuiteVisitor):

    def __init__(self, pattern):
        self.matcher = Matcher(pattern)

    def start_suite(self, suite):
        """Remove tests that match the given pattern."""
        suite.tests = [t for t in suite.tests if not self._is_excluded(t)]

    def _is_excluded(self, test):
        return self.matcher.match(test.name) or self.matcher.match(test.longname)

    def end_suite(self, suite):
        """Remove suites that are empty after removing tests."""
        suite.suites = [s for s in suite.suites if s.test_count > 0]

    def visit_test(self, test):
        """Avoid visiting tests and their keywords to save a little time."""
        pass

Assuming the above modifier is in a file named ExcludeTests.py, it could be used like this:
假设上面的修饰符在一个名为ExcludeTests.py文件中,它可以这样使用:

# Exclude test named 'Example'.
robot --prerunmodifier path/to/ExcludeTests.py:Example tests.robot

# Exclude all tests ending with 'something'.
robot --prerunmodifier path/to/ExcludeTests.py:*something tests.robot

Example: Disable setups and teardowns
示例:禁用设置和拆卸

Sometimes when debugging tests it can be useful to disable setups or teardowns. This can be accomplished by editing the test data, but pre-run modifiers make it easy to do that temporarily for a single run:
有时候,在调试测试时,禁用设置或拆卸可能很有用。这可以通过编辑测试数据来完成,但是运行前修改器可以很容易地为单次运行临时执行:

"""Pre-run modifiers for disabling suite and test setups and teardowns."""

from robot.api import SuiteVisitor


class SuiteSetup(SuiteVisitor):

    def start_suite(self, suite):
        suite.setup = None


class SuiteTeardown(SuiteVisitor):

    def start_suite(self, suite):
        suite.teardown = None


class TestSetup(SuiteVisitor):

    def start_test(self, test):
        test.setup = None


class TestTeardown(SuiteVisitor):

    def start_test(self, test):
        test.teardown = None

Assuming that the above modifiers are all in a file named disable.py and this file is in the module search path, setups and teardowns could be disabled, for example, as follows:
假设上述修饰符都在名为disable.py的文件中,并且该文件位于模块搜索路径中,则可以禁用设置和拆卸,例如,如下所示:

# Disable suite teardowns.
robot --prerunmodifier disable.SuiteTeardown tests.robot

# Disable both test setups and teardowns by using '--prerunmodifier' twice.
robot --prerunmodifier disable.TestSetup --prerunmodifier disable.TestTeardown tests.robot

Note 注意

Prior to Robot Framework 4.0 setup and teardown were accessed via the intermediate keywords attribute and, for example, suite setup was disabled like suite.keywords.setup = None.
在Robot Framework 4.0之前,设置拆卸是通过中间关键字属性访问的,例如,套件设置被禁用,如suite.keywords.setup = None

3.5.9   Controlling console output
控制台输出

There are various command line options to control how test execution is reported on the console.
有各种命令行选项可以控制如何在控制台上报告测试执行。

Console output type 控制台输出类型

The overall console output type is set with the --console option. It supports the following case-insensitive values:
整个控制台输出类型是用--console选项设置的。它支持以下不区分大小写的值:

verbose
Every test suite and test case is reported individually. This is the default.
每个测试套件和测试用例都单独报告。这是默认设置。
dotted
Only show . for passed test, F for failed tests, s for skipped tests and x for tests which are skipped because test execution exit. Failed tests are listed separately after execution. This output type makes it easy to see are there any failures during execution even if there would be a lot of tests.
只是作秀对于通过的测试,F表示失败的测试,s表示跳过的测试,x表示由于测试执行退出而跳过的测试。失败的测试在执行后单独列出。这种输出类型可以很容易地看到执行过程中是否有任何失败,即使有很多测试。
quiet
No output except for errors and warnings.
除了错误和警告之外,没有输出。
none
No output whatsoever. Useful when creating a custom output using, for example, listeners.
没有任何输出。在使用侦听器等创建自定义输出时很有用。

Separate convenience options --dotted (-.) and --quiet are shortcuts for --console dotted and --console quiet, respectively.
单独的便利选项--点(-.)--quiet分别是--console dotted--console quiet的快捷方式。

Examples: 示例如下:

robot --console quiet tests.robot
robot --dotted tests.robot

Console width 控制台宽度

The width of the test execution output in the console can be set using the option --consolewidth (-W). The default width is 78 characters.
控制台中测试执行输出的宽度可以使用选项--consolewidth(-W)设置。默认宽度为78个字符。

Tip 尖端

On many UNIX-like machines you can use handy $COLUMNS environment variable like --consolewidth $COLUMNS.
在许多类UNIX机器上,您可以使用方便的$COLUMNS环境变量,如--consolewide $COLUMNS

Console colors 控制台颜色

The --consolecolors (-C) option is used to control whether colors should be used in the console output. Colors are implemented using ANSI colors except on Windows where, by default, Windows APIs are used instead.
--consolecolors(-C) 选项用于控制是否应在控制台输出中使用颜色。颜色是使用ANSI颜色实现的,但在Windows上除外,默认情况下,Windows API被使用。

This option supports the following case-insensitive values:
此选项支持以下不区分大小写的值:

auto
Colors are enabled when outputs are written into the console, but not when they are redirected into a file or elsewhere. This is the default.
颜色在输出写入控制台时启用,但在输出重定向到文件或其他位置时不启用。这是默认设置。
on
Colors are used also when outputs are redirected. Does not work on Windows.
当输出被重定向时也使用颜色。不适用于Windows。
ansi
Same as on but uses ANSI colors also on Windows. Useful, for example, when redirecting output to a program that understands ANSI colors.
相同,但在Windows上也使用ANSI颜色。例如,在将输出重定向到理解ANSI颜色的程序时很有用。
off
Colors are disabled. 颜色已禁用。

Console markers 控制台标记

Special markers . (success) and F (failure) are shown on the console when using the verbose output and top level keywords in test cases end. The markers allow following the test execution in high level, and they are erased when test cases end.
特殊标记当在测试用例end中使用详细输出和顶级关键字时,控制台上会显示F(成功)和F(失败)。这些标记允许跟踪高级别的测试执行,并且当测试用例结束时它们会被删除。

It is possible to configure when markers are used with --consolemarkers (-K) option. It supports the following case-insensitive values:
可以通过--consolemarkers(-K)选项配置何时使用标记。它支持以下不区分大小写的值:

auto
Markers are enabled when the standard output is written into the console, but not when it is redirected into a file or elsewhere. This is the default.
标记在标准输出写入控制台时启用,但在将其重定向到文件或其他位置时不启用。这是默认设置。
on
Markers are always used. 标记总是使用。
off
Markers are disabled. 标记已禁用。

3.5.10   Setting listeners 3.5.10设置监听器

Listeners can be used to monitor the test execution. When they are taken into use from the command line, they are specified using the --listener command line option. The value can either be a path to a listener or a listener name. See the Listener interface section for more details about importing listeners and using them in general.
侦听器可用于监视测试执行。当从命令行使用它们时,使用--listener命令行选项指定它们。该值可以是侦听器的路径或侦听器名称。有关导入侦听器和一般使用侦听器的更多详细信息,请参见“侦听器接口”部分。

3.6   Output files 3.6输出文件

Several output files are created when tests are executed, and all of them are somehow related to test results. This section discusses what outputs are created, how to configure where they are created, and how to fine-tune their contents.
执行测试时会创建几个输出文件,所有这些文件都与测试结果有某种关系。本节讨论创建哪些输出、如何配置它们的创建位置以及如何微调它们的内容。

3.6.1   Different output files
3.6.1不同的输出文件

This section explains what different output files can be created and how to configure where they are created. Output files are configured using command line options, which get the path to the output file in question as an argument. A special value NONE (case-insensitive) can be used to disable creating a certain output file.
本节说明可以创建哪些不同的输出文件以及如何配置创建这些文件的位置。输出文件是使用命令行选项配置的,这些选项将获取有问题的输出文件的路径作为参数。一个特殊的值NONE(不区分大小写)可以用来禁止创建特定的输出文件。

Output directory 输出目录

All output files can be set using an absolute path, in which case they are created to the specified place, but in other cases, the path is considered relative to the output directory. The default output directory is the directory where the execution is started from, but it can be altered with the --outputdir (-d) option. The path set with this option is, again, relative to the execution directory, but can naturally be given also as an absolute path. Regardless of how a path to an individual output file is obtained, its parent directory is created automatically, if it does not exist already.
所有输出文件都可以使用绝对路径设置,在这种情况下,它们被创建到指定的位置,但在其他情况下,路径被认为是相对于输出目录。默认的输出目录是开始执行的目录,但可以使用--outputdir(-d)选项进行更改。使用此选项设置的路径也是相对于执行目录的,但也可以自然地作为绝对路径给出。无论如何获得单个输出文件的路径,如果它不存在,它的父目录将自动创建。

Output file 输出文件

Output files contain all the test execution results in machine readable XML format. Log, report and xUnit files are typically generated based on them, and they can also be combined and otherwise post-processed with Rebot.
输出文件包含所有机器可读XML格式的测试执行结果。日志报告xUnit文件通常基于它们生成,它们也可以组合在一起,或者使用Rebot进行后处理。

Tip 尖端

Generating report and xUnit files as part of test execution does not require processing output files after execution. Disabling log generation when running tests can thus save memory.
作为测试执行的一部分生成报告xUnit文件不需要在执行后处理输出文件。因此,在运行测试时禁用日志生成可以节省内存。

The command line option --output (-o) determines the path where the output file is created relative to the output directory. The default name for the output file, when tests are run, is output.xml.
命令行选项--output(-o)确定相对于输出目录创建输出文件的路径。运行测试时,输出文件的默认名称为output.xml

When post-processing outputs with Rebot, new output files are not created unless the --output option is explicitly used.
当使用Rebot对输出进行后处理时,除非显式使用--output选项,否则不会创建新的输出文件。

It is possible to disable creation of the output file when running tests by giving a special value NONE to the --output option. If no outputs are needed, they should all be explicitly disabled using --output NONE --report NONE --log NONE.
通过给--output选项一个特殊的值NONE,如果不需要输出,则应使用--output NONE --report NONE --log NONE显式禁用所有输出。

The XML output file structure is documented in the robot.xsd schema file.
XML输出文件结构记录在robot.xsd模式文件中。

Note 注意

Starting from Robot Framework 7.0, Rebot can read and write JSON output files. The plan is to enhance the support for JSON output files in the future so that they could be created already during execution. For more details see issue #3423.
从Robot Framework 7.0开始,Rebot可以读写JSON输出文件。计划是在未来增强对JSON输出文件的支持,以便它们可以在执行过程中创建。更多详情请参见问题#3423

Legacy output file format
传统输出文件格式

There were some backwards incompatible changes to the output file format in Robot Framework 7.0. To make it possible to use new Robot Framework versions with external tools that are not yet updated to support the new format, there is a --legacyoutput option that produces output files that are compatible with Robot Framework 6.x and earlier. Robot Framework itself can process output files both in the old and in the new formats.
Robot Framework 7.0中的输出文件格式有一些向后不兼容的更改。为了使新的Robot Framework版本能够与尚未更新以支持新格式的外部工具一起使用,有一个--legacyoutput选项可以生成与Robot Framework 6.x和更早版本兼容的输出文件。Robot Framework本身可以处理新旧格式的输出文件。

We hope that external tools are updated soon, but we plan to support this option at least until Robot Framework 8.0. If you encounter tools that are not compatible, please inform the tool developers about changes.
我们希望外部工具能很快更新,但我们计划至少在Robot Framework 8.0之前支持此选项。如果您遇到不兼容的工具,请通知工具开发人员有关更改。

Log file 日志文件

Log files contain details about the executed test cases in HTML format. They have a hierarchical structure showing test suite, test case and keyword details. Log files are needed nearly every time when test results are to be investigated in detail. Even though log files also have statistics, reports are better for getting an higher-level overview.
日志文件以HTML格式包含有关已执行测试用例的详细信息。它们具有显示测试套件、测试用例和关键字细节的层次结构。当需要详细调查测试结果时,几乎每次都需要日志文件。尽管日志文件也有统计数据,但报告更适合获得更高级别的概述。

The command line option --log (-l) determines where log files are created. Unless the special value NONE is used, log files are always created and their default name is log.html.
命令行选项--log(-l)确定创建日志文件的位置。除非使用特殊值NONE,否则始终会创建日志文件,并且其默认名称为log.html

src/ExecutingTestCases/log_passed.png

An example of beginning of a log file
日志文件开头的示例

src/ExecutingTestCases/log_failed.png

An example of a log file with keyword details visible
关键字详细信息可见的日志文件示例

src/ExecutingTestCases/log_skipped.png

An example of a log file with skipped and passed tests
包含跳过的测试和通过的测试的日志文件示例

Report file 报告文件

Report files contain an overview of the test execution results in HTML format. They have statistics based on tags and executed test suites, as well as a list of all executed test cases. When both reports and logs are generated, the report has links to the log file for easy navigation to more detailed information. It is easy to see the overall test execution status from report, because its background color is green, if all tests pass and bright red if any test fails. Background can also be yellow, which means that all tests were skipped.
报告文件包含HTML格式的测试执行结果概述。它们具有基于标记和已执行测试套件的统计数据,以及所有已执行测试用例的列表。当生成报告和日志时,报告具有指向日志文件的链接,以便轻松导航到更详细的信息。从报告中可以很容易地看到整个测试执行状态,因为如果所有测试都通过,则其背景颜色为绿色,如果任何测试失败,则为亮红色。背景也可以是黄色,这意味着跳过了所有测试。

The command line option --report (-r) determines where report files are created. Similarly as log files, reports are always created unless NONE is used as a value, and their default name is report.html.
命令行选项--report(-r)确定创建报告文件的位置。与日志文件类似,除非使用NONE作为值,否则始终会创建报告,其默认名称为report.html

src/ExecutingTestCases/report_passed.png

An example report file of successful test execution
成功执行测试的示例报告文件

src/ExecutingTestCases/report_failed.png

An example report file of failed test execution
失败的测试执行的示例报告文件

XUnit compatible result file
XUnit兼容结果文件

XUnit result files contain the test execution summary in xUnit compatible XML format. These files can thus be used as an input for external tools that understand xUnit reports. For example, Jenkins continuous integration server supports generating statistics based on xUnit compatible results.
XUnit结果文件包含xUnit兼容XML格式的测试执行摘要。因此,这些文件可以用作理解xUnit报告的外部工具的输入。例如,Jenkins持续集成服务器支持基于xUnit兼容的结果生成统计信息。

Tip 尖端

Jenkins also has a separate Robot Framework plugin.
Jenkins还有一个单独的Robot Framework插件

XUnit output files are not created unless the command line option --xunit (-x) is used explicitly. This option requires a path to the generated xUnit file, relatively to the output directory, as a value.
除非显式使用命令行选项--xunit(-x),否则不会创建XUnit输出文件。这个选项需要一个到生成的xUnit文件的路径,相对于输出目录,作为一个值。

XUnit output files were changed pretty heavily in Robot Framework 5.0. They nowadays contain separate <testsuite> elements for each suite, <testsuite> elements have timestamp attribute, and suite documentation and metadata is stored as <property> elements.
XUnit输出文件在Robot Framework 5.0中被修改得相当严重。它们现在包含每个套件的单独的<testsuite>元素,<testsuite>元素具有timestamp属性,套件文档元数据存储为<property>元素。

Debug file 调试文件

Debug files are plain text files that are written during the test execution. All messages got from test libraries are written to them, as well as information about started and ended test suites, test cases and keywords. Debug files can be used for monitoring the test execution. This can be done using, for example, a separate fileviewer.py tool, or in UNIX-like systems, simply with the tail -f command.
测试文件是在测试执行过程中编写的纯文本文件。从测试库获得的所有消息都被写入到测试库中,以及关于开始和结束的测试套件、测试用例和关键字的信息。测试文件可用于监视测试执行。例如,可以使用单独的fileviewer.py工具或在类UNIX系统中只需使用 tail -f 命令即可完成此操作。

Debug files are not created unless the command line option --debugfile (-b) is used explicitly.
除非显式使用命令行选项--debugfile(-B),否则不会创建Debug文件。

Timestamping output files
为输出文件添加时间戳

All output files generated by Robot Framework itself can be automatically timestamped with the option --timestampoutputs (-T). When this option is used, a timestamp in the format YYYYMMDD-hhmmss is placed between the extension and the base name of each file. The example below would, for example, create output files like output-20080604-163225.xml and mylog-20080604-163225.html:
Robot Framework本身生成的所有输出文件都可以使用选项--timestampoutputs(-T)自动添加时间戳。使用此选项时,在每个文件的扩展名和基名称之间放置YYYYMMDD-hhmmss格式的时间戳。例如,下面的示例将创建输出文件,如output-20080604-163225.xmlmylog-20080604-163225.html

robot --timestampoutputs --log mylog.html --report NONE tests.robot

Setting titles 设置标题

The default titles for logs and reports are generated by prefixing the name of the top-level test suite with Test Log or Test Report. Custom titles can be given from the command line using the options --logtitle and --reporttitle, respectively.
日志报告的默认标题是通过在顶级测试套件的名称前面加上TestLogTestReport来生成的。可以分别使用选项--logtitle--reporttitle从命令行给出自定义标题。

Example: 范例:

robot --logtitle "Smoke Test Log" --reporttitle "Smoke Test Report" --include smoke my_tests/

Note 注意

Prior to Robot Framework 3.1, underscores in the given titles were converted to spaces. Nowadays spaces need to be escaped or quoted like in the example above.
在Robot Framework 3.1之前,给定标题中的下划线被转换为空格。现在,空格需要转义或引用,就像上面的例子一样。

Setting background colors
设置背景颜色

By default the report file has red background if there are failures, green background if there are passed tests and possibly some skipped ones, and a yellow background if all tests are skipped or no tests have been run. These colors can be customized by using the --reportbackground command line option, which takes two or three colors separated with a colon as an argument:
默认情况下,如果存在失败,则报告文件的背景为红色;如果存在通过的测试和可能跳过的测试,则报告文件的背景为绿色;如果跳过所有测试或未运行测试,则报告文件的背景为黄色。这些颜色可以通过使用--reportbackground命令行选项进行自定义,该选项将两种或三种颜色作为参数,并以冒号分隔:

--reportbackground blue:red
--reportbackground blue:red:orange
--reportbackground #00E:#E00

If you specify two colors, the first one will be used instead of the default green (pass) color and the second instead of the default red (fail). This allows, for example, using blue instead of green to make backgrounds easier to separate for color blind people.
如果指定两种颜色,则将使用第一种颜色代替默认的绿色(通过)颜色,使用第二种颜色代替默认的红色(失败)。例如,这允许使用蓝色而不是绿色来使色盲人群更容易分离背景。

If you specify three colors, the first two have same semantics as earlier and the last one replaces the default yellow (skip) color.
如果指定三种颜色,前两种颜色的语义与前面的相同,最后一种颜色将替换默认的黄色(跳过)颜色。

The specified colors are used as a value for the body element's background CSS property. The value is used as-is and can be a HTML color name (e.g. red), a hexadecimal value (e.g. #f00 or #ff0000), or an RGB value (e.g. rgb(255,0,0)). The default green, red and yellow colors are specified using hexadecimal values #9e9, #f66 and #fed84f, respectively.
指定的颜色用作body元素的backgroundCSS属性的值。该值按原样使用,可以是HTML颜色名称(例如红色)、十六进制值(例如#f00#ff0000)或RGB值(例如rgb(255,0,0))。默认的绿色、红色和黄色分别使用十六进制值#9e9#f66#fed84f指定。

3.6.2   Log levels 3.6.2日志级别

Available log levels 可用日志级别

Messages in log files can have different log levels. Some of the messages are written by Robot Framework itself, but also executed keywords can log information using different levels. The available log levels are:
日志文件中的消息可以具有不同的日志级别。有些消息是由Robot Framework自己编写的,但执行的关键字也可以使用不同的级别记录信息。可用的日志级别为:

FAIL
Used when a keyword fails. Can be used only by Robot Framework itself.
当关键字失败时使用。只能由Robot Framework本身使用。
WARN
Used to display warnings. They shown also in the console and in the Test Execution Errors section in log files, but they do not affect the test case status.
用于显示警告。它们也显示在控制台和日志文件的测试执行错误部分中,但它们不影响测试用例状态。
INFO
The default level for normal messages. By default, messages below this level are not shown in the log file.
普通消息的默认级别。默认情况下,日志文件中不显示低于此级别的消息。
DEBUG
Used for debugging purposes. Useful, for example, for logging what libraries are doing internally. When a keyword fails, a traceback showing where in the code the failure occurred is logged using this level automatically.
用于调试目的。例如,用于记录库在内部做什么。当关键字失败时,将使用此级别自动记录回溯,显示代码中发生失败的位置。
TRACE
More detailed debugging level. The keyword arguments and return values are automatically logged using this level.
更详细的调试级别。使用此级别自动记录关键字参数和返回值。

Setting log level 设置日志级别

By default, log messages below the INFO level are not logged, but this threshold can be changed from the command line using the --loglevel (-L) option. This option takes any of the available log levels as an argument, and that level becomes the new threshold level. A special value NONE can also be used to disable logging altogether.
默认情况下,不记录低于INFO级别的日志消息,但可以使用--loglevel(-L)选项从命令行更改此阈值。此选项将任何可用的日志级别作为参数,该级别将成为新的阈值级别。也可以使用特殊值NONE来完全禁用日志记录。

It is possible to use the --loglevel option also when post-processing outputs with Rebot. This allows, for example, running tests initially with the TRACE level, and generating smaller log files for normal viewing later with the INFO level. By default all the messages included during execution will be included also with Rebot. Messages ignored during the execution cannot be recovered.
在使用Rebot对输出进行后处理时,也可以使用--loglevel选项。例如,这允许最初使用TRACE级别运行测试,并生成较小的日志文件,以便稍后使用INFO级别进行正常查看。默认情况下,执行过程中包含的所有消息也将包含在Rebot中。无法恢复执行期间忽略的消息。

Another possibility to change the log level is using the BuiltIn keyword Set Log Level in the test data. It takes the same arguments as the --loglevel option, and it also returns the old level so that it can be restored later, for example, in a test teardown.
更改日志级别的另一种可能性是在测试数据中使用BuiltIn关键字SetLogLevel。它采用与--loglevel选项相同的参数,并且它还返回旧级别,以便稍后可以恢复,例如,在测试拆除中。

Visible log level 可见对数级

If the log file contains messages at DEBUG or TRACE levels, a visible log level drop down is shown in the upper right corner. This allows users to remove messages below chosen level from the view. This can be useful especially when running test at TRACE level.
如果日志文件包含DEBUGTRACE级别的消息,则会在右上角显示一个可见的日志级别下拉列表。这允许用户从视图中删除低于所选级别的消息。这在TRACE级别运行测试时尤其有用。

src/ExecutingTestCases/visible_log_level.png

An example log showing the visible log level drop down
显示可见日志级别下拉列表的示例日志

By default the drop down will be set at the lowest level in the log file, so that all messages are shown. The default visible log level can be changed using --loglevel option by giving the default after the normal log level separated by a colon:
默认情况下,下拉列表将设置在日志文件的最低级别,以便显示所有消息。可以使用--loglevel选项更改默认可见日志级别,方法是在正常日志级别后给出默认值,并用冒号分隔:

--loglevel DEBUG:INFO

In the above example, tests are run using level DEBUG, but the default visible level in the log file is INFO.
在上面的示例中,测试是使用级别DEBUG运行的,但日志文件中的默认可见级别是INFO

3.6.3   Splitting logs 3.6.3劈木

Normally the log file is just a single HTML file. When the amount of the test cases increases, the size of the file can grow so large that opening it into a browser is inconvenient or even impossible. Hence, it is possible to use the --splitlog option to split parts of the log into external files that are loaded transparently into the browser when needed.
通常,日志文件只是一个HTML文件。当测试用例的数量增加时,文件的大小可能会变得非常大,以至于在浏览器中打开它是不方便的,甚至是不可能的。因此,可以使用--splitlog选项将日志的各个部分拆分为外部文件,以便在需要时透明地加载到浏览器中。

The main benefit of splitting logs is that individual log parts are so small that opening and browsing the log file is possible even if the amount of the test data is very large. A small drawback is that the overall size taken by the log file increases.
拆分日志的主要好处是,单个日志部分非常小,即使测试数据量非常大,也可以打开和浏览日志文件。一个小缺点是日志文件的总体大小会增加。

Technically the test data related to each test case is saved into a JavaScript file in the same folder as the main log file. These files have names such as log-42.js where log is the base name of the main log file and 42 is an incremented index.
从技术上讲,与每个测试用例相关的测试数据都保存在与主日志文件相同的文件夹中的JavaScript文件中。这些文件的名称如log-42.js,其中log是主日志文件的基本名称,42是递增索引。

Note 注意

When copying the log files, you need to copy also all the log-*.js files or some information will be missing.
复制日志文件时,您需要同时复制所有log-*.js文件,否则会丢失某些信息。

3.6.4   Configuring statistics
3.6.4配置统计信息

There are several command line options that can be used to configure and adjust the contents of the Statistics by Tag, Statistics by Suite and Test Details by Tag tables in different output files. All these options work both when executing test cases and when post-processing outputs.
有几个命令行选项可用于配置和调整不同输出文件中的“按标签统计”、“按套件统计”和“按标签测试详细信息”表的内容。所有这些选项在执行测试用例和后处理输出时都有效。

Configuring displayed suite statistics
配置显示的套件统计信息

When a deeper suite structure is executed, showing all the test suite levels in the Statistics by Suite table may make the table somewhat difficult to read. By default all suites are shown, but you can control this with the command line option --suitestatlevel which takes the level of suites to show as an argument:
当执行更深层次的套件结构时,在“Statistics by Suite”表中显示所有测试套件级别可能会使该表有点难以阅读。默认情况下,所有套件都会显示,但您可以使用命令行选项--suitestatlevel来控制,该选项将显示的套件级别作为参数:

--suitestatlevel 3

Including and excluding tag statistics
包括和排除标记统计信息

When many tags are used, the Statistics by Tag table can become quite congested. If this happens, the command line options --tagstatinclude and --tagstatexclude can be used to select which tags to display, similarly as --include and --exclude are used to select test cases:
当使用许多标签时,“标签统计信息”表可能会变得非常拥挤。如果发生这种情况,可以使用命令行选项--tagstatinclude--tagstatexclude来选择要显示的标签,类似于使用--include--exclude选择测试用例

--tagstatinclude some-tag --tagstatinclude another-tag
--tagstatexclude owner-*
--tagstatinclude prefix-* --tagstatexclude prefix-13

Generating combined tag statistics
生成组合标记统计信息

The command line option --tagstatcombine can be used to generate aggregate tags that combine statistics from multiple tags. The combined tags are specified using tag patterns where * and ? are supported as wildcards and AND, OR and NOT operators can be used for combining individual tags or patterns together.
命令行选项--tagstat联合收割机可用于生成聚合标记,该标记可将多个标记的统计信息联合收割机组合在一起。组合标记是使用标记模式指定的,其中 *支持通配符,ANDORNOT运算符可用于将单个标记或模式组合在一起。

The following examples illustrate creating combined tag statistics using different patterns, and the figure below shows a snippet of the resulting Statistics by Tag table:
以下示例说明了如何使用不同模式创建组合标记统计信息,下图显示了生成的Statistics by Tag表的片段:

--tagstatcombine owner-*
--tagstatcombine smokeANDmytag
--tagstatcombine smokeNOTowner-janne*
src/ExecutingTestCases/tagstatcombine.png

Examples of combined tag statistics
组合标记统计信息的示例

As the above example illustrates, the name of the added combined statistic is, by default, just the given pattern. If this is not good enough, it is possible to give a custom name after the pattern by separating them with a colon (:):
正如上面的示例所示,默认情况下,添加的组合统计量的名称就是给定的模式。如果这还不够好,可以在模式后给出一个自定义名称,用冒号()分隔它们:

--tagstatcombine "prio1ORprio2:High priority tests"

Note 注意

Prior to Robot Framework 3.1, underscores in the custom name were converted to spaces. Nowadays spaces need to be escaped or quoted like in the example above.
在Robot Framework 3.1之前,自定义名称中的下划线被转换为空格。现在,空格需要转义或引用,就像上面的例子一样。

Adding documentation to tags
向标签添加文档

Tags can be given a documentation with the command line option --tagdoc, which takes an argument in the format tag:doc. tag is the name of the tag to assign the documentation to, and it can also be a simple pattern matching multiple tags. doc is the assigned documentation. It can contain simple HTML formatting.
可以使用命令行选项--tagdoc为标记提供一个文档,该选项接受格式为tag:doc的参数。tag是要将文档分配到的标记的名称,它也可以是匹配多个标记的简单模式doc是指定的文档。它可以包含简单的HTML格式

The given documentation is shown with matching tags in the Test Details by Tag table, and as a tool tip for these tags in the Statistics by Tag table. If one tag gets multiple documentations, they are combined together and separated with an ampersand.
给定的文档在“Test Details by Tag”(按标签列出的测试详细信息)表格中显示为匹配标签,并在“Statistics by Tag”(按标签列出的统计信息)表格中显示为这些标签的工具提示。如果一个标签获得多个文档,它们将组合在一起,并使用&号分隔。

Examples: 示例如下:

--tagdoc mytag:Example
--tagdoc "regression:*See* http://info.html"
--tagdoc "owner-*:Original author"

Note 注意

Prior to Robot Framework 3.1, underscores in the documentation were converted to spaces. Nowadays spaces need to be escaped or quoted like in the examples above.
在Robot Framework 3.1之前,文档中的下划线被转换为空格。现在,空格需要转义或引用,就像上面的例子一样。

3.6.5   Removing and flattening keywords
3.6.5删除和扁平化关键字

Most of the content of output files comes from keywords and their log messages. When creating higher level reports, log files are not necessarily needed at all, and in that case keywords and their messages just take space unnecessarily. Log files themselves can also grow overly large, especially if they contain FOR loops or other constructs that repeat certain keywords multiple times.
输出文件的大部分内容来自关键字及其日志消息。在创建更高级别的报告时,根本不需要日志文件,在这种情况下,关键字及其消息只会不必要地占用空间。日志文件本身也可能变得过大,特别是当它们包含FOR循环或其他多次重复某些关键字的结构时。

In these situations, command line options --removekeywords and --flattenkeywords can be used to dispose or flatten unnecessary keywords. They can be used both when executing test cases and when post-processing outputs. When used during execution, they only affect the log file, not the XML output file. With rebot they affect both logs and possibly generated new output XML files.
在这些情况下,可以使用命令行选项--removekeywords--removekeywords来处理或扁平化不必要的关键字。它们可以在执行测试用例后处理输出时使用。在执行期间使用时,它们只影响日志文件,而不影响XML输出文件。使用rebot,它们会影响日志,并可能会生成新的输出XML文件。

Removing keywords 删除关键字

The --removekeywords option removes keywords and their messages altogether. It has the following modes of operation, and it can be used multiple times to enable multiple modes. Keywords that contain errors or warnings are not removed except when using the ALL mode.
--removekeywords 选项将删除关键字及其消息。它具有以下操作模式,并且可以多次使用以启用多种模式。除非使用ALL模式,否则不会删除包含错误或警告的关键字。

ALL
Remove data from all keywords unconditionally.
无条件删除所有关键字中的数据。
PASSED
Remove keyword data from passed test cases. In most cases, log files created using this option contain enough information to investigate possible failures.
从通过的测试用例中删除关键字数据。在大多数情况下,使用此选项创建的日志文件包含足够的信息来调查可能的故障。
FOR
Remove all passed iterations from FOR loops except the last one.
FOR循环中删除所有传递的迭代,除了最后一个。
WHILE
Remove all passed iterations from WHILE loops except the last one.
从WHILE循环中删除所有传递的迭代除了最后一个。
WUKS
Remove all failing keywords inside BuiltIn keyword Wait Until Keyword Succeeds except the last one.
删除内置关键字内的所有失败关键字等待,直到关键字成功,除了最后一个。
NAME:<pattern>
Remove data from all keywords matching the given pattern regardless the keyword status. The pattern is matched against the full name of the keyword, prefixed with the possible library or resource file name like MyLibrary.Keyword Name. The pattern is case, space, and underscore insensitive, and it supports simple patterns with *, ? and [] as wildcards.
从所有与给定模式匹配的关键字中删除数据,而不管关键字状态如何。该模式与关键字的全名匹配,并以可能的库或资源文件名(如MyLibrary.KeywordName)作为前缀。该模式不区分大小写、空格和下划线,并且支持带有 *[]作为通配符。
TAG:<pattern>
Remove data from keywords with tags that match the given pattern. Tags are case and space insensitive and they can be specified using tag patterns where *, ? and [] are supported as wildcards and AND, OR and NOT operators can be used for combining individual tags or patterns together. Can be used both with library keyword tags and user keyword tags.
从带有与给定模式匹配的标记的关键字中删除数据。标记不区分大小写和空格,可以使用标记模式指定它们,其中 *,?和[]支持作为通配符,AND、OR和NOT运算符可用于将单个标记或模式组合在一起。可以与库关键字标记和用户关键字标记一起使用。

Examples: 示例如下:

rebot --removekeywords all --output removed.xml output.xml
robot --removekeywords passed --removekeywords for tests.robot
robot --removekeywords name:HugeKeyword --removekeywords name:resource.* tests.robot
robot --removekeywords tag:huge tests.robot

Removing keywords is done after parsing the output file and generating an internal model based on it. Thus it does not reduce memory usage as much as flattening keywords.
删除关键字是在解析输出文件并基于其生成内部模型之后完成的。因此,它不会像扁平化关键字那样减少内存使用。

Flattening keywords 扁平化关键字

The --flattenkeywords option flattens matching keywords. In practice this means that matching keywords get all log messages from their child keywords, recursively, and child keywords are discarded otherwise. Flattening supports the following modes:
--keywords 选项用于搜索匹配的关键字。在实践中,这意味着匹配关键字递归地从其子关键字获取所有日志消息,否则子关键字将被丢弃。展平支持以下模式:

FOR
Flatten FOR loops fully.
完全展平FOR循环
WHILE
Flatten WHILE loops fully.
完全展平WHILE循环
ITERATION
Flatten individual FOR and WHILE loop iterations.
使单独的FORWHILE循环迭代变平。
FORITEM
Deprecated alias for ITERATION.
ITERATION的已弃用别名。
NAME:<pattern>
Flatten keywords matching the given pattern. Pattern matching rules are same as when removing keywords using the NAME:<pattern> mode.
展平与给定模式匹配的关键字。模式匹配规则与使用NAME:<pattern>模式删除关键字时相同。
TAG:<pattern>
Flatten keywords with tags matching the given pattern. Pattern matching rules are same as when removing keywords using the TAG:<pattern> mode.
用匹配给定模式的标签来扁平化关键字。模式匹配规则与使用TAG:<pattern>模式删除关键字时相同。

Examples: 示例如下:

robot --flattenkeywords name:HugeKeyword --flattenkeywords name:resource.* tests.robot
rebot --flattenkeywords foritem --output flattened.xml original.xml

Flattening keywords is done already when the output file is parsed initially. This can save a significant amount of memory especially with deeply nested keyword structures.
在最初解析输出文件时,已经完成了关键字的扁平化。这可以节省大量的内存,特别是对于深度嵌套的关键字结构。

Flattening keyword during execution time
在执行期间展平关键字

Starting from Robot Framework 6.1, it is possible to enable the keyword flattening during the execution time. This can be done only on an user keyword level by defining the reserved tag robot:flatten as a keyword tag. Using this tag will work similarly as the command line option described in the previous chapter, e.g. all content except for log messages is removed from under the keyword having the tag. One important difference is that in this case, the removed content is not written to the output file at all, and thus cannot be accessed at later time.
从Robot Framework 6.1开始,可以在执行期间启用关键字扁平化。这只能通过将保留标签robot:flatten定义为关键字标签来在用户关键字级别上完成。使用此标签的工作方式与上一章中描述的命令行选项类似,例如,从具有标签的关键字下删除除日志消息之外的所有内容。一个重要的区别是,在这种情况下,删除的内容根本不会写入输出文件,因此以后无法访问。

Some examples 一些示例

*** Keywords ***
Flattening affects this keyword and all it's children
    [Tags]    robot:flatten
    Log    something
    FOR     ${i}     IN RANGE     2
         Log    The message is preserved but for loop iteration is not
    END

*** Settings ***
# Flatten content of all uer keywords
Keyword Tags    robot:flatten

3.6.6   Automatically expanding keywords
3.6.6自动扩展关键字

Keywords that have passed are closed in the log file by default. Thus information they contain is not visible unless you expand them. If certain keywords have important information that should be visible when the log file is opened, you can use the --expandkeywords option to set keywords automatically expanded in log file similar to failed keywords. Expanding supports the following modes:
默认情况下,已通过的关键字在日志文件中关闭。因此,除非展开它们,否则它们包含的信息是不可见的。如果某些关键字具有在打开日志文件时应该可见的重要信息,则可以使用--expandkeywords选项将在日志文件中自动展开的关键字设置为类似于失败的关键字。展开支持以下模式:

NAME:<pattern>
Expand keywords matching the given pattern. Pattern matching rules are same as when removing keywords using the NAME:<pattern> mode.
展开与给定模式匹配的关键字。模式匹配规则与使用NAME:<pattern>模式删除关键字时相同。
TAG:<pattern>
Expand keywords with tags matching the given pattern. Pattern matching rules are same as when removing keywords using the TAG:<pattern> mode.
使用与给定模式匹配的标签扩展关键字。模式匹配规则与使用TAG:<pattern>模式删除关键字时相同。

If you need to expand keywords matching different names or patterns, you can use the --expandkeywords multiple times.
如果需要扩展匹配不同名称或模式的关键字,可以多次使用--expandkeywords

Examples: 示例如下:

robot --expandkeywords name:SeleniumLibrary.CapturePageScreenshot tests.robot
rebot --expandkeywords tag:example --expandkeywords tag:another output.xml

Note 注意

The --expandkeywords option is new in Robot Framework 3.2.
--expandkeywords 选项是Robot Framework 3.2中的新选项。

3.6.7   Setting start and end time of execution
3.6.7设置执行开始和结束时间

When combining outputs using Rebot, it is possible to set the start and end time of the combined test suite using the options --starttime and --endtime, respectively. This is convenient, because by default, combined suites do not have these values. When both the start and end time are given, the elapsed time is also calculated based on them. Otherwise the elapsed time is got by adding the elapsed times of the child test suites together.
当使用Rebot组合输出时,可以分别使用选项--starttime--endtime设置组合测试套件的开始和结束时间。这很方便,因为默认情况下,组合套件没有这些值。当同时给出开始和结束时间时,也会根据它们计算经过的时间。否则,通过将子测试套件的运行时间相加得到运行时间。

It is also possible to use the above mentioned options to set start and end times for a single suite when using Rebot. Using these options with a single output always affects the elapsed time of the suite.
使用Rebot时,也可以使用上述选项设置单个套件的开始和结束时间。将这些选项与单个输出一起使用总是会影响套件的运行时间。

Times must be given as timestamps in the format YYYY-MM-DD hh:mm:ss.mil, where all separators are optional and the parts from milliseconds to hours can be omitted. For example, 2008-06-11 17:59:20.495 is equivalent both to 20080611-175920.495 and 20080611175920495, and also mere 20080611 would work.
时间必须以YYYY-MM-DD hh:mm:ss.mil格式的时间戳形式给出,其中所有分隔符都是可选的,从毫秒到小时的部分可以省略。例如,2008-06-11 17:59:20.495既相当于20080611-175920.495,也相当于20080611175920495,而且只有20080611才有效。

Examples: 示例如下:

rebot --starttime 20080611-17:59:20.495 output1.xml output2.xml
rebot --starttime 20080611-175920 --endtime 20080611-180242 *.xml
rebot --starttime 20110302-1317 --endtime 20110302-11418 myoutput.xml

3.6.8   Limiting error message length in reports
3.6.8限制报告中的错误消息长度

If a test case fails and has a long error message, the message shown in reports is automatically cut from the middle to keep reports easier to read. By default messages longer than 40 lines are cut, but that can be configured by using the --maxerrorlines command line option. The minimum value for this option is 10, and it is also possible to use a special value NONE to show the full message.
如果一个测试用例失败了,并且有一个很长的错误消息,报告中显示的消息会自动从中间剪掉,以使报告更容易阅读。默认情况下,长度超过40行的消息将被剪切,但可以使用--maxerrorlines命令行选项进行配置。此选项的最小值为10,也可以使用特殊值NONE来显示完整的消息。

Full error messages are always visible in log files as messages of the failed keywords.
完整的错误消息在日志文件中始终显示为失败关键字的消息。

Note 注意

The --maxerrorlines option is new in Robot Framework 3.1.
--maxerrorlines 选项是Robot Framework 3.1中的新选项。

3.6.9   Programmatic modification of results
3.6.9成果的方案修改

If the provided built-in features to modify results are not enough, Robot Framework makes it possible to do custom modifications programmatically. This is accomplished by creating a model modifier and activating it using the --prerebotmodifier option.
如果提供的内置功能不足以修改结果,Robot Framework可以通过编程方式进行自定义修改。这是通过创建模型修改器并使用--prerebotmodifier选项激活它来实现的。

This functionality works nearly exactly like programmatic modification of test data that can be enabled with the --prerunmodifier option. The obvious difference is that this time modifiers operate with the result model, not the running model. For example, the following modifier marks all passed tests that have taken more time than allowed as failed:
此功能的工作方式几乎与使用--prerunmodifier选项启用的测试数据编程修改完全相同。明显的区别是,这次修改器使用结果模型,而不是运行模型。例如,下面的修饰符将所有花费的时间超过允许时间的已通过测试标记为失败:

from robot.api import SuiteVisitor


class ExecutionTimeChecker(SuiteVisitor):

    def __init__(self, max_seconds: float):
        self.max_milliseconds = max_seconds * 1000

    def visit_test(self, test):
        if test.status == 'PASS' and test.elapsedtime > self.max_milliseconds:
            test.status = 'FAIL'
            test.message = 'Test execution took too long.'

If the above modifier would be in file ExecutionTimeChecker.py, it could be used, for example, like this:
如果上面的修饰符在文件ExecutionTimeChecker.py中,它可以这样使用:

# Specify modifier as a path when running tests. Maximum time is 42 seconds.
robot --prerebotmodifier path/to/ExecutionTimeChecker.py:42 tests.robot

# Specify modifier as a name when using Rebot. Maximum time is 3.14 seconds.
# ExecutionTimeChecker.py must be in the module search path.
rebot --prerebotmodifier ExecutionTimeChecker:3.14 output.xml

If more than one model modifier is needed, they can be specified by using the --prerebotmodifier option multiple times. When executing tests, it is possible to use --prerunmodifier and --prerebotmodifier options together.
如果需要多个模型修改器,可以通过多次使用--prerebotmodifier选项来指定它们。在执行测试时,可以同时使用--prerunmodifier--prerebotmodifier选项。

Note 注意

Argument conversion based on type hints like max_seconds: float in the above example is new in Robot Framework 4.0 and requires Python 3.
基于类型提示的参数转换,如上面示例中的max_seconds:float,是Robot Framework 4.0中的新功能,需要Python 3。

3.6.10   System log 3.6.10系统日志

Robot Framework has its own plain-text system log where it writes information about
Robot Framework有自己的纯文本系统日志,它在其中写入有关

  • Processed and skipped test data files
    已处理和跳过的测试数据文件
  • Imported test libraries, resource files and variable files
    导入的测试库、资源文件和变量文件
  • Executed test suites and test cases
    已执行的测试套件和测试用例
  • Created outputs 创建的产出

Normally users never need this information, but it can be useful when investigating problems with test libraries or Robot Framework itself. A system log is not created by default, but it can be enabled by setting the environment variable ROBOT_SYSLOG_FILE so that it contains a path to the selected file.
通常用户不需要这些信息,但在调查测试库或Robot Framework本身的问题时,这些信息可能很有用。默认情况下不创建系统日志,但可以通过设置环境变量 ROBOT_SYSLOG_FILE 来启用系统日志,使其包含所选文件的路径。

A system log has the same log levels as a normal log file, with the exception that instead of FAIL it has the ERROR level. The threshold level to use can be altered using the ROBOT_SYSLOG_LEVEL environment variable like shown in the example below. Possible unexpected errors and warnings are written into the system log in addition to the console and the normal log file.
系统日志与普通日志文件具有相同的日志级别,不同之处在于它的级别不是FAIL而是ERROR。要使用的阈值水平可以使用 ROBOT_SYSLOG_LEVEL 环境变量进行更改,如下面的示例所示。除了控制台和正常日志文件外,可能的意外错误和警告也会写入系统日志。

#!/bin/bash

export ROBOT_SYSLOG_FILE=/tmp/syslog.txt
export ROBOT_SYSLOG_LEVEL=DEBUG

robot --name Syslog_example path/to/tests

4   Extending Robot Framework
4扩展机器人框架

4.1   Creating test libraries
4.1创建测试库

Robot Framework's actual testing capabilities are provided by test libraries. There are many existing libraries, some of which are even bundled with the core framework, but there is still often a need to create new ones. This task is not too complicated because, as this chapter illustrates, Robot Framework's library API is simple and straightforward.
Robot Framework的实际测试功能由测试库提供。有许多现有的库,其中一些甚至与核心框架捆绑在一起,但仍然经常需要创建新的库。该任务并不太复杂,因为正如本章所示,Robot框架的库API简单明了。

4.1.1   Introduction 4.1.1引言

Supported programming languages
支持的编程语言

Robot Framework itself is written with Python and naturally test libraries extending it can be implemented using the same language. It is also possible to implement libraries with C using Python C API, although it is often easier to interact with C code from Python libraries using ctypes module.
Robot Framework本身是用Python编写的,自然可以使用相同的语言实现扩展它的测试库。也可以使用Python C API用C实现库,尽管使用ctypes模块与Python库中的C代码交互通常更容易。

Libraries implemented using Python can also act as wrappers to functionality implemented using other programming languages. A good example of this approach is the Remote library, and another widely used approaches is running external scripts or tools as separate processes.
使用Python实现的库也可以充当使用其他编程语言实现的功能的包装器。这种方法的一个很好的例子是远程库,另一种广泛使用的方法是将外部脚本或工具作为单独的进程运行。

Different test library APIs
不同的测试库API

Robot Framework has three different test library APIs.
Robot Framework有三个不同的测试库API。

Static API 静态API

The simplest approach is having a module or a class with functions/methods which map directly to keyword names. Keywords also take the same arguments as the methods implementing them. Keywords report failures with exceptions, log by writing to standard output and can return values using the return statement.
最简单的方法是拥有一个模块或类,其中包含直接映射到关键字名称的函数/方法。关键字也采用与实现它们的方法相同的参数。关键字报告异常失败,通过写入标准输出记录日志,并可以使用return语句返回值

Dynamic API 动态API

Dynamic libraries are classes that implement a method to get the names of the keywords they implement, and another method to execute a named keyword with given arguments. The names of the keywords to implement, as well as how they are executed, can be determined dynamically at runtime, but reporting the status, logging and returning values is done similarly as in the static API.
动态库是实现一个方法来获取它们实现的关键字的名称的类,以及另一个方法来执行具有给定参数的命名关键字。要实现的关键字的名称以及它们的执行方式可以在运行时动态确定,但是报告状态、记录和返回值的方式与静态API中的方式类似。

Hybrid API 混合API

This is a hybrid between the static and the dynamic API. Libraries are classes with a method telling what keywords they implement, but those keywords must be available directly. Everything else except discovering what keywords are implemented is similar as in the static API.
这是静态和动态API的混合体。库是具有方法的类,该方法告诉它们实现了哪些关键字,但这些关键字必须直接可用。除了发现实现了哪些关键字之外,其他所有操作都与静态API类似。

All these APIs are described in this chapter. Everything is based on how the static API works, so its functions are discussed first. How the dynamic library API and the hybrid library API differ from it is then discussed in sections of their own.
所有这些API都在本章中描述。一切都基于静态API的工作方式,因此首先讨论其功能。动态库API混合库API与它的不同之处将在各自的章节中讨论。

4.1.2   Creating test library class or module
4.1.2创建测试库类或模块

Test libraries can be implemented as Python modules or classes.
测试库可以实现为Python模块或类。

Library name 库名称

The name of a test library that is used when a library is imported is the same as the name of the module or class implementing it. For example, if you have a Python module MyLibrary (that is, file MyLibrary.py), it will create a library with name MyLibrary.
导入库时使用的测试库的名称与实现它的模块或类的名称相同。例如,如果您有一个Python模块MyLibrary(即文件MyLibrary.py),它将创建一个名为MyLibrary的库。

Python classes are always inside a module. If the name of a class implementing a library is the same as the name of the module, Robot Framework allows dropping the class name when importing the library. For example, class MyLib in MyLib.py file can be used as a library with just name MyLib. This also works with submodules so that if, for example, parent.MyLib module has class MyLib, importing it using just parent.MyLib works. If the module name and class name are different, libraries must be taken into use using both module and class names, such as mymodule.MyLibrary or parent.submodule.MyLib.
Python类总是在模块中。如果实现库的类的名称与模块的名称相同,则Robot Framework允许在导入库时删除类名。例如,MyLib.py文件中的类MyLib可以用作仅命名为MyLib的库。这也适用于子模块,例如,如果parent.MyLib模块具有类MyLib,则只使用parent.MyLib导入它。如果模块名和类名不同,则必须同时使用模块名和类名来使用库,例如mymodule.MyLibraryparent.submodule.MyLib

Tip 尖端

If the library name is really long, it is recommended to give the library a simpler alias by using AS.
如果库名称很长,建议使用AS为库指定一个更简单的别名

Providing arguments to libraries
为图书馆提供论据

All test libraries implemented as classes can take arguments. These arguments are specified in the Setting section after the library name, and when Robot Framework creates an instance of the imported library, it passes them to its constructor. Libraries implemented as a module cannot take any arguments, so trying to use those results in an error.
所有实现为类的测试库都可以接受参数。这些参数在库名称之后的设置部分中指定,当Robot Framework创建导入库的实例时,它将它们传递给其构造函数。作为模块实现的库不能接受任何参数,因此尝试使用这些参数会导致错误。

The number of arguments needed by the library is the same as the number of arguments accepted by the library's constructor. The default values and variable number of arguments work similarly as with keyword arguments. Arguments passed to the library, as well as the library name itself, can be specified using variables, so it is possible to alter them, for example, from the command line.
库所需的参数数量与库的构造函数所接受的参数数量相同。参数的默认值和可变数量与关键字参数的工作方式类似。传递给库的参数以及库名称本身可以使用变量指定,因此可以从命令行等方式更改它们。

*** Settings ***
Library    MyLibrary     10.0.0.1    8080
Library    AnotherLib    ${VAR}

Example implementations for the libraries used in the above example:
以上示例中使用的库的示例实现:

from example import Connection

class MyLibrary:

    def __init__(self, host, port=80):
        self._conn = Connection(host, int(port))

    def send_message(self, message):
        self._conn.send(message)
class AnotherLib:

    def __init__(self, environment):
        self.environment = environment

    def do_something(self):
        if self.environment == 'test':
            # do something in test environment
        else:
            # do something in other environments

Library scope 库作用域

Libraries implemented as classes can have an internal state, which can be altered by keywords and with arguments to the constructor of the library. Because the state can affect how keywords actually behave, it is important to make sure that changes in one test case do not accidentally affect other test cases. These kind of dependencies may create hard-to-debug problems, for example, when new test cases are added and they use the library inconsistently.
作为类实现的库可以有一个内部状态,它可以通过关键字和库构造函数的参数来改变。因为状态会影响关键字的实际行为,所以确保一个测试用例中的更改不会意外地影响其他测试用例是很重要的。这种依赖关系可能会产生难以调试的问题,例如,当添加新的测试用例时,它们使用的库不一致。

Robot Framework attempts to keep test cases independent from each other: by default, it creates new instances of test libraries for every test case. However, this behavior is not always desirable, because sometimes test cases should be able to share a common state. Additionally, all libraries do not have a state and creating new instances of them is simply not needed.
Robot Framework试图保持测试用例彼此独立:默认情况下,它为每个测试用例创建测试库的新实例。然而,这种行为并不总是可取的,因为有时测试用例应该能够共享一个公共状态。此外,所有库都没有状态,因此根本不需要创建它们的新实例。

Test libraries can control when new libraries are created with a class attribute ROBOT_LIBRARY_SCOPE . This attribute must be a string and it can have the following three values:
测试库可以控制何时使用类属性ROBOT_LIBRARY_SCOPE创建新库。此属性必须是字符串,并且可以具有以下三个值:

TEST

A new instance is created for every test case. A possible suite setup and suite teardown share yet another instance.
为每个测试用例创建一个新实例。一个可能的套件安装和套件拆卸共享另一个实例。

Prior to Robot Framework 3.2 this value was TEST CASE, but nowadays TEST is recommended. Because all unrecognized values are considered same as TEST, both values work with all versions. For the same reason it is possible to also use value TASK if the library is targeted for RPA usage more than testing. TEST is also the default value if the ROBOT_LIBRARY_SCOPE attribute is not set.
在Robot Framework 3.2之前,此值为TEST CASE,但现在建议使用TEST。由于所有无法识别的值都被视为与TEST相同,因此这两个值都适用于所有版本。出于同样的原因,如果库的目标是RPA使用而不是测试,则也可以使用值ASK。如果未设置ROBOT_LIBRARY_SCOPE属性,TEST也是默认值。

SUITE

A new instance is created for every test suite. The lowest-level test suites, created from test case files and containing test cases, have instances of their own, and higher-level suites all get their own instances for their possible setups and teardowns.
为每个测试套件创建一个新实例。从测试用例文件创建并包含测试用例的最低级别的测试套件有自己的实例,而更高级别的套件都有自己的实例,用于可能的设置和拆卸。

Prior to Robot Framework 3.2 this value was TEST SUITE. That value still works, but SUITE is recommended with libraries targeting Robot Framework 3.2 and newer.
在Robot Framework 3.2之前,此值为TEST SUITE。该值仍然有效,但建议将SUITE用于针对Robot Framework 3.2及更新版本的库。

GLOBAL
Only one instance is created during the whole test execution and it is shared by all test cases and test suites. Libraries created from modules are always global.
在整个测试执行过程中只创建一个实例,并且它由所有测试用例和测试套件共享。从模块创建的库始终是全局的。

Note 注意

If a library is imported multiple times with different arguments, a new instance is created every time regardless the scope.
如果一个库使用不同的参数被多次导入,则无论作用域如何,每次都会创建一个新实例。

When the SUITE or GLOBAL scopes are used with libraries that have a state, it is recommended that libraries have some special keyword for cleaning up the state. This keyword can then be used, for example, in a suite setup or teardown to ensure that test cases in the next test suites can start from a known state. For example, SeleniumLibrary uses the GLOBAL scope to enable using the same browser in different test cases without having to reopen it, and it also has the Close All Browsers keyword for easily closing all opened browsers.
SUITEGLOBAL作用域与具有状态的库一起使用时,建议库使用一些特殊的关键字来清除状态。这个关键字可以被使用,例如,在一个套件设置或拆卸中,以确保下一个测试套件中的测试用例可以从一个已知的状态开始。例如,SeleniumLibrary使用GLOBAL作用域来支持在不同的测试用例中使用相同的浏览器,而不必重新打开它,它还具有Close All Browsers关键字,用于轻松关闭所有打开的浏览器。

Example library using the SUITE scope:
使用SUITE作用域的示例库:

class ExampleLibrary:
    ROBOT_LIBRARY_SCOPE = 'SUITE'

    def __init__(self):
        self._counter = 0

    def count(self):
        self._counter += 1
        print(self._counter)

    def clear_counter(self):
        self._counter = 0

Library version 库版本

When a test library is taken into use, Robot Framework tries to determine its version. This information is then written into the syslog to provide debugging information. Library documentation tool Libdoc also writes this information into the keyword documentations it generates.
当测试库被使用时,Robot Framework会尝试确定其版本。然后将此信息写入系统日志以提供调试信息。库文档工具Libdoc也将此信息写入其生成的关键字文档中。

Version information is read from attribute ROBOT_LIBRARY_VERSION, similarly as library scope is read from ROBOT_LIBRARY_SCOPE. If ROBOT_LIBRARY_VERSION does not exist, information is tried to be read from __version__ attribute. These attributes must be class or module attributes, depending whether the library is implemented as a class or a module.
版本信息从属性ROBOT_LIBRARY_VERSION读取,类似于从ROBOT_LIBRARY_SCOPE读取库作用域。如果ROBOT_LIBRARY_VERSION不存在,则尝试从__version__属性读取信息。这些属性必须是类或模块属性,具体取决于库是作为类还是模块实现的。

An example module using __version__:
使用__version__的示例模块:

__version__ = '0.1'

def keyword():
    pass

Documentation format 文件格式

Library documentation tool Libdoc supports documentation in multiple formats. If you want to use something else than Robot Framework's own documentation formatting, you can specify the format in the source code using ROBOT_LIBRARY_DOC_FORMAT attribute similarly as scope and version are set with their own ROBOT_LIBRARY_* attributes.
库文档工具Libdoc支持多种格式的文档。如果您想使用Robot Framework自己的文档格式之外的其他格式,则可以使用ROBOT_LIBRARY_DOC_FORMAT属性在源代码中指定格式,这与使用其自己的ROBOT_LIBRARY_*属性设置范围版本类似。

The possible case-insensitive values for documentation format are ROBOT (default), HTML, TEXT (plain text), and reST (reStructuredText). Using the reST format requires the docutils module to be installed when documentation is generated.
文档格式可能不区分大小写的值有ROBOT(默认)、HTMLTEXT(纯文本)和reSTreStructuredText)。使用reST格式需要在生成文档时安装docutils模块。

Setting the documentation format is illustrated by the following example that uses reStructuredText format. See Documenting libraries section and Libdoc chapter for more information about documenting test libraries in general.
下面使用reStructuredText格式的示例说明了如何设置文档格式。请参阅文档化库部分和Libdoc章节以获取更多关于文档化测试库的信息。

"""A library for *documentation format* demonstration purposes.

This documentation is created using reStructuredText__. Here is a link
to the only \`Keyword\`.

__ http://docutils.sourceforge.net
"""

ROBOT_LIBRARY_DOC_FORMAT = 'reST'


def keyword():
    """**Nothing** to see here. Not even in the table below.

    =======  =====  =====
    Table    here   has
    nothing  to     see.
    =======  =====  =====
    """
    pass

Library acting as listener
图书馆作为倾听者

Listener interface allows external listeners to get notifications about test execution. They are called, for example, when suites, tests, and keywords start and end. Sometimes getting such notifications is also useful for test libraries, and they can register a custom listener by using ROBOT_LIBRARY_LISTENER attribute. The value of this attribute should be an instance of the listener to use, possibly the library itself.
测试接口允许外部侦听器获取有关测试执行的通知。例如,在套件、测试和关键字开始和结束时调用它们。有时候,获得这样的通知对于测试库也很有用,它们可以通过使用ROBOT_LIBRARY_LISTENER属性注册自定义侦听器。该属性的值应该是要使用的侦听器的实例,可能是库本身。

For more information and examples see Libraries as listeners section.
有关更多信息和示例,请参见作为侦听器的库部分。

@library decorator
@librarydecorator

An easy way to configure libraries implemented as classes is using the robot.api.deco.library class decorator. It allows configuring library's scope, version, custom argument converters, documentation format and listener with optional arguments scope, version, converter, doc_format and listener, respectively. When these arguments are used, they set the matching ROBOT_LIBRARY_SCOPE, ROBOT_LIBRARY_VERSION, ROBOT_LIBRARY_CONVERTERS, ROBOT_LIBRARY_DOC_FORMAT and ROBOT_LIBRARY_LISTENER attributes automatically:
配置实现为类的库的一种简单方法是使用robot.API.deco.library类装饰器。它允许配置库的范围版本自定义参数转换器文档格式监听器,分别具有可选的参数范围版本转换器doc_format监听器。当使用这些参数时,它们会自动设置匹配的ROBOT_LIBRARY_SCOPEROBOT_LIBRARY_VERSIONROBOT_LIBRARY_CONVERTERSROBOT_LIBRARY_DOC_FORMATROBOT_LIBRARY_LISTENER属性:

from robot.api.deco import library

from example import Listener


@library(scope='GLOBAL', version='3.2b1', doc_format='reST', listener=Listener())
class Example:
    # ...

The @library decorator also disables the automatic keyword discovery by setting the ROBOT_AUTO_KEYWORDS argument to False by default. This means that it is mandatory to decorate methods with the @keyword decorator to expose them as keywords. If only that behavior is desired and no further configuration is needed, the decorator can also be used without parenthesis like:
@library装饰器还通过将ROBOT_REPORT_KEYWORDS参数默认设置为False来禁用自动关键字发现。这意味着必须使用@keyword装饰器来装饰方法,以将它们公开为关键字。如果只需要这种行为,不需要进一步的配置,装饰器也可以在没有括号的情况下使用,比如:

from robot.api.deco import library


@library
class Example:
    # ...

If needed, the automatic keyword discovery can be enabled by using the auto_keywords argument:
如果需要,可以使用auto_keywords参数启用自动关键字发现:

from robot.api.deco import library


@library(scope='GLOBAL', auto_keywords=True)
class Example:
    # ...

The @library decorator only sets class attributes ROBOT_LIBRARY_SCOPE, ROBOT_LIBRARY_VERSION, ROBOT_LIBRARY_CONVERTERS, ROBOT_LIBRARY_DOC_FORMAT and ROBOT_LIBRARY_LISTENER if the respective arguments scope, version, converters, doc_format and listener are used. The ROBOT_AUTO_KEYWORDS attribute is set always. When attributes are set, they override possible existing class attributes.
如果使用了相应的参数scopeversionconvertersdoc_formatlistener,则@library装饰器仅设置类属性ROBOT_LIBRARY_SCOPEROBOT_LIBRARY_VERSIONROBOT_LIBRARY_CONVERTERS、ROBOT_LIBRARY_DOC_FORMAT和ROBOT_LIBRARY_LISTENERROBOT_KEY_WORDS属性始终设置。当属性被设置时,它们覆盖可能存在的类属性。

Note 注意

The @library decorator is new in Robot Framework 3.2 and converters argument is new in Robot Framework 5.0.
@librarydecorator是Robot Framework 3.2中的新功能,converters参数是Robot Framework 5.0中的新功能。

4.1.3   Creating keywords 4.1.3创建关键字

What methods are considered keywords
哪些方法被认为是关键字

When the static library API is used, Robot Framework uses introspection to find out what keywords the library class or module implements. By default it excludes methods and functions starting with an underscore. All the methods and functions that are not ignored are considered keywords. For example, the library below implements a single keyword My Keyword.
当使用静态库API时,Robot Framework使用内省来找出库类或模块实现了哪些关键字。默认情况下,它排除以下划线开头的方法和函数。所有没有被忽略的方法和函数都被认为是关键字。例如,下面的库实现了一个关键字My Keyword

class MyLibrary:

    def my_keyword(self, arg):
        return self._helper_method(arg)

    def _helper_method(self, arg):
        return arg.upper()

Limiting public methods becoming keywords
限制公共方法成为关键字

Automatically considering all public methods and functions keywords typically works well, but there are cases where it is not desired. There are also situations where keywords are created when not expected. For example, when implementing a library as class, it can be a surprise that also methods in possible base classes are considered keywords. When implementing a library as a module, functions imported into the module namespace becoming keywords is probably even a bigger surprise.
自动考虑所有公共方法和函数关键字通常效果很好,但在某些情况下并不需要这样做。还有一些情况下,关键字是在不期望的时候创建的。例如,当将库实现为类时,可能令人惊讶的是,可能的基类中的方法也被认为是关键字。当将库实现为模块时,导入到模块名称空间中的函数变成关键字可能更令人惊讶。

This section explains how to prevent methods and functions becoming keywords.
本节解释如何防止方法和函数成为关键字。

Class based libraries 基于类的库

When a library is implemented as a class, it is possible to tell Robot Framework not to automatically expose methods as keywords by setting the ROBOT_AUTO_KEYWORDS attribute to the class with a false value:
当一个库被实现为一个类时,可以通过将ROBOT_PROJECT_KEYWORDS属性设置为一个false值来告诉Robot Framework不要自动将方法公开为关键字:

class Example:
    ROBOT_AUTO_KEYWORDS = False

When the ROBOT_AUTO_KEYWORDS attribute is set like this, only methods that have explicitly been decorated with the @keyword decorator or otherwise have the robot_name attribute become keywords. The @keyword decorator can also be used for setting a custom name, tags and argument types to the keyword.
ROBOT_keyword_KEYWORDS属性被这样设置时,只有那些已经显式地用@keyword装饰器装饰的方法或者具有robot_name属性的方法才成为关键字。@keyworddecorator也可以用来为关键字设置自定义名称标签参数类型

Although the ROBOT_AUTO_KEYWORDS attribute can be set to the class explicitly, it is more convenient to use the @library decorator that sets it to False by default:
虽然ROBOT_REPORT_KEYWORDS属性可以显式地设置为类,但使用@library装饰器将其默认设置为False会更方便:

from robot.api.deco import keyword, library


@library
class Example:

    @keyword
    def this_is_keyword(self):
        pass

    @keyword('This is keyword with custom name')
    def xxx(self):
        pass

    def this_is_not_keyword(self):
        pass

Note 注意

Both limiting what methods become keywords using the ROBOT_AUTO_KEYWORDS attribute and the @library decorator are new in Robot Framework 3.2.
使用ROBOT_PROJECT_KEYWORDS属性和@library装饰器限制哪些方法成为关键字是Robot Framework 3.2中的新功能。

Another way to explicitly specify what keywords a library implements is using the dynamic or the hybrid library API.
显式指定库实现的关键字的另一种方法是使用动态混合库API。

Module based libraries 基于模块的库

When implementing a library as a module, all functions in the module namespace become keywords. This is true also with imported functions, and that can cause nasty surprises. For example, if the module below would be used as a library, it would contain a keyword Example Keyword, as expected, but also a keyword Current Thread.
当将库实现为模块时,模块命名空间中的所有函数都成为关键字。对于导入的函数也是如此,这可能会导致令人讨厌的意外。例如,如果下面的模块将被用作库,它将包含关键字Example Keyword,正如预期的那样,但也包含关键字Current Thread

from threading import current_thread


def example_keyword():
    print('Running in thread "%s".' % current_thread().name)

A simple way to avoid imported functions becoming keywords is to only import modules (e.g. import threading) and to use functions via the module (e.g threading.current_thread()). Alternatively functions could be given an alias starting with an underscore at the import time (e.g. from threading import current_thread as _current_thread).
避免导入的函数成为关键字的一个简单方法是只导入模块(例如导入线程),并通过模块使用函数(例如threading.current_thread())。或者,函数可以在导入时被赋予一个以下划线开头的别名(例如,从线程导入current_thread as _current_thread)。

A more explicit way to limit what functions become keywords is using the module level __all__ attribute that Python itself uses for similar purposes. If it is used, only the listed functions can be keywords. For example, the library below implements only one keyword Example Keyword:
一种更明确的限制函数成为关键字的方法是使用模块级别的__all__属性,Python本身也使用该属性来实现类似的目的。如果使用它,则只有列出的函数可以是关键字。例如,下面的库只实现了一个关键字Example Keyword

from threading import current_thread


__all__ = ['example_keyword']


def example_keyword():
    print('Running in thread "%s".' % current_thread().name)

def this_is_not_keyword():
    pass

If the library is big, maintaining the __all__ attribute when keywords are added, removed or renamed can be a somewhat big task. Another way to explicitly mark what functions are keywords is using the ROBOT_AUTO_KEYWORDS attribute similarly as it can be used with class based libraries. When this attribute is set to a false value, only functions explicitly decorated with the @keyword decorator become keywords. For example, also this library implements only one keyword Example Keyword:
如果库很大,在添加、删除或重命名关键字时维护__all__属性可能是一项比较大的任务。另一种显式标记哪些函数是关键字的方法是使用ROBOT_PROJECT_KEYWORDS属性,类似于它可以用于基于类的库。当此属性设置为false值时,只有使用@keyword装饰器显式装饰的函数才成为关键字。例如,这个库也只实现了一个关键字Example Keyword

from threading import current_thread

from robot.api.deco import keyword


ROBOT_AUTO_KEYWORDS = False


@keyword
def example_keyword():
    print('Running in thread "%s".' % current_thread().name)

def this_is_not_keyword():
    pass

Note 注意

Limiting what functions become keywords using ROBOT_AUTO_KEYWORDS is a new feature in Robot Framework 3.2.
使用ROBOT_KEY_WORDS限制哪些函数成为关键字是Robot Framework 3.2中的一项新功能。

Using @not_keyword decorator
使用@not_keyword装饰器

Functions in modules and methods in classes can be explicitly marked as "not keywords" by using the @not_keyword decorator. When a library is implemented as a module, this decorator can also be used to avoid imported functions becoming keywords.
模块中的函数和类中的方法可以通过使用@not_keyword装饰器显式地标记为“not keywords”。当一个库被实现为一个模块时,这个装饰器也可以用来避免导入的函数变成关键字。

from threading import current_thread

from robot.api.deco import not_keyword


not_keyword(current_thread)    # Don't expose `current_thread` as a keyword.


def example_keyword():
    print('Running in thread "%s".' % current_thread().name)

@not_keyword
def this_is_not_keyword():
    pass

Using the @not_keyword decorator is pretty much the opposite way to avoid functions or methods becoming keywords compared to disabling the automatic keyword discovery with the @library decorator or by setting the ROBOT_AUTO_KEYWORDS to a false value. Which one to use depends on the context.
使用@not_keyword装饰器与使用@library装饰器禁用自动关键字发现或通过将ROBOT_PROJECT_KEYWORDS设置为false值相比,避免函数或方法成为关键字的方式几乎相反。使用哪一个取决于上下文。

Note 注意

The @not_keyword decorator is new in Robot Framework 3.2.
@not_keyword装饰器是Robot Framework 3.2中的新功能。

Keyword names 关键字名称

Keyword names used in the test data are compared with method names to find the method implementing these keywords. Name comparison is case-insensitive, and also spaces and underscores are ignored. For example, the method hello maps to the keyword name Hello, hello or even h e l l o. Similarly both the do_nothing and doNothing methods can be used as the Do Nothing keyword in the test data.
将测试数据中使用的关键字名称与方法名称进行比较,以找到实现这些关键字的方法。名称比较不区分大小写,空格和下划线也会被忽略。例如,方法hello映射到关键字名称Hellohello甚至h e l l o。类似地,do_nothingdoNothing方法都可以用作测试数据中的Do Nothing关键字。

Example library implemented as a module in the MyLibrary.py file:
示例库在MyLibrary.py文件中实现为模块:

def hello(name):
    print("Hello, %s!" % name)

def do_nothing():
    pass

The example below illustrates how the example library above can be used. If you want to try this yourself, make sure that the library is in the module search path.
下面的示例说明了如何使用上面的示例库。如果您想亲自尝试,请确保该库位于模块搜索路径中。

*** Settings ***
Library    MyLibrary

*** Test Cases ***
My Test
    Do Nothing
    Hello    world
Setting custom name 设置自定义名称

It is possible to expose a different name for a keyword instead of the default keyword name which maps to the method name. This can be accomplished by setting the robot_name attribute on the method to the desired custom name:
可以为关键字公开不同的名称,而不是映射到方法名称的默认关键字名称。这可以通过将方法上的robot_name属性设置为所需的自定义名称来实现:

def login(username, password):
  # ...

login.robot_name = 'Login via user panel'
*** Test Cases ***
My Test
    Login Via User Panel    ${username}    ${password}

Instead of explicitly setting the robot_name attribute like in the above example, it is typically easiest to use the @keyword decorator:
不像上面的例子那样显式地设置robot_name属性,通常最简单的方法是使用@keyword装饰器

from robot.api.deco import keyword


@keyword('Login via user panel')
def login(username, password):
      # ...

Using this decorator without an argument will have no effect on the exposed keyword name, but will still set the robot_name attribute. This allows marking methods to expose as keywords without actually changing keyword names. Methods that have the robot_name attribute also create keywords even if the method name itself would start with an underscore.
不带参数地使用这个装饰器对暴露的关键字名称没有影响,但仍然会设置robot_name属性。这允许将方法标记为关键字,而无需实际更改关键字名称。具有robot_name属性的方法也会创建关键字,即使方法名称本身以下划线开头。

Setting a custom keyword name can also enable library keywords to accept arguments using the embedded arguments syntax.
设置自定义关键字名称还可以使库关键字使用嵌入参数语法接受参数。

Keyword tags 关键字标签

Library keywords and user keywords can have tags. Library keywords can define them by setting the robot_tags attribute on the method to a list of desired tags. Similarly as when setting custom name, it is easiest to set this attribute by using the @keyword decorator:
库关键字和用户关键字可以有标签。库关键字可以通过将方法上的robot_tags属性设置为所需标记的列表来定义它们。与设置自定义名称时类似,使用@关键字装饰器来设置此属性是最简单的:

from robot.api.deco import keyword


@keyword(tags=['tag1', 'tag2'])
def login(username, password):
    # ...

@keyword('Custom name', ['tags', 'here'])
def another_example():
    # ...

Another option for setting tags is giving them on the last line of keyword documentation with Tags: prefix and separated by a comma. For example:
设置标签的另一个选项是在关键字文档的最后一行使用Tags:前缀并以逗号分隔。举例来说:

def login(username, password):
    """Log user in to SUT.

    Tags: tag1, tag2
    """
    # ...

Keyword arguments 关键字参数

With a static and hybrid API, the information on how many arguments a keyword needs is got directly from the method that implements it. Libraries using the dynamic library API have other means for sharing this information, so this section is not relevant to them.
对于静态和混合API,关于关键字需要多少参数的信息直接从实现它的方法中获得。使用动态库API的库有其他方法来共享此信息,因此本节与它们无关。

The most common and also the simplest situation is when a keyword needs an exact number of arguments. In this case, the method simply take exactly those arguments. For example, a method implementing a keyword with no arguments takes no arguments either, a method implementing a keyword with one argument also takes one argument, and so on.
最常见也是最简单的情况是当关键字需要确切数量的参数时。在这种情况下,该方法只接受这些参数。例如,一个方法实现了一个不带参数的关键字,也不带参数,一个方法实现了一个带参数的关键字,也带一个参数,等等。

Example keywords taking different numbers of arguments:
示例关键字采用不同数量的参数:

def no_arguments():
    print("Keyword got no arguments.")

def one_argument(arg):
    print("Keyword got one argument '%s'." % arg)

def three_arguments(a1, a2, a3):
    print("Keyword got three arguments '%s', '%s' and '%s'." % (a1, a2, a3))

Default values to keywords
关键字的默认值

It is often useful that some of the arguments that a keyword uses have default values.
关键字使用的某些参数具有默认值通常很有用。

In Python a method has always exactly one implementation and possible default values are specified in the method signature. The syntax, which is familiar to all Python programmers, is illustrated below:
在Python中,一个方法总是只有一个实现,可能的默认值在方法签名中指定。所有Python程序员都熟悉的语法如下所示:

def one_default(arg='default'):
    print("Argument has value %s" % arg)

def multiple_defaults(arg1, arg2='default 1', arg3='default 2'):
    print("Got arguments %s, %s and %s" % (arg1, arg2, arg3))

The first example keyword above can be used either with zero or one arguments. If no arguments are given, arg gets the value default. If there is one argument, arg gets that value, and calling the keyword with more than one argument fails. In the second example, one argument is always required, but the second and the third one have default values, so it is possible to use the keyword with one to three arguments.
上面的第一个示例关键字可以与零个或一个参数一起使用。如果没有给出参数,arg将获得默认值。如果只有一个参数,arg将获取该值,使用多个参数调用关键字将失败。在第二个示例中,始终需要一个参数,但第二个和第三个参数具有默认值,因此可以将关键字与一到三个参数一起使用。

*** Test Cases ***
Defaults
    One Default
    One Default    argument
    Multiple Defaults    required arg
    Multiple Defaults    required arg    optional
    Multiple Defaults    required arg    optional 1    optional 2

Variable number of arguments (*varargs)
变量数量(*varargs

Robot Framework supports also keywords that take any number of arguments.
Robot Framework还支持采用任意数量参数的关键字。

Python supports methods accepting any number of arguments. The same syntax works in libraries and, as the examples below show, it can also be combined with other ways of specifying arguments:
Python支持接受任意数量参数的方法。同样的语法也适用于库,如下面的例子所示,它也可以与其他指定参数的方式结合使用:

def any_arguments(*args):
    print("Got arguments:")
    for arg in args:
        print(arg)

def one_required(required, *others):
    print("Required: %s\nOthers:" % required)
    for arg in others:
        print(arg)

def also_defaults(req, def1="default 1", def2="default 2", *rest):
    print(req, def1, def2, rest)
*** Test Cases ***
Varargs
    Any Arguments
    Any Arguments    argument
    Any Arguments    arg 1    arg 2    arg 3    arg 4    arg 5
    One Required     required arg
    One Required     required arg    another arg    yet another
    Also Defaults    required
    Also Defaults    required    these two    have defaults
    Also Defaults    1    2    3    4    5    6

Free keyword arguments (**kwargs)
自由关键字参数(**kwargs

Robot Framework supports Python's **kwargs syntax. How to use use keywords that accept free keyword arguments, also known as free named arguments, is discussed under the Creating test cases section. In this section we take a look at how to create such keywords.
Robot Framework支持Python的 **kwargs语法。如何使用接受自由关键字参数(也称为自由命名参数)的use关键字,将在创建测试用例一节中讨论。在本节中,我们来看看如何创建这样的关键字。

If you are already familiar how kwargs work with Python, understanding how they work with Robot Framework test libraries is rather simple. The example below shows the basic functionality:
如果您已经熟悉kwargs如何与Python一起工作,那么了解它们如何与Robot Framework测试库一起工作是相当简单的。下面的示例显示了基本功能:

def example_keyword(**stuff):
    for name, value in stuff.items():
        print(name, value)
*** Test Cases ***
Keyword Arguments
    Example Keyword    hello=world        # Logs 'hello world'.
    Example Keyword    foo=1    bar=42    # Logs 'foo 1' and 'bar 42'.

Basically, all arguments at the end of the keyword call that use the named argument syntax name=value, and that do not match any other arguments, are passed to the keyword as kwargs. To avoid using a literal value like foo=quux as a free keyword argument, it must be escaped like foo\=quux.
基本上,在关键字调用的末尾,所有使用命名参数语法name=value,并且不匹配任何其他参数的参数都作为kwargs传递给关键字。为了避免使用像foo=quux这样的文字值作为自由关键字参数,它必须像foo\=quux那样进行转义

The following example illustrates how normal arguments, varargs, and kwargs work together:
下面的示例说明了普通参数、varargs和kwargs如何协同工作:

def various_args(arg=None, *varargs, **kwargs):
    if arg is not None:
        print('arg:', arg)
    for value in varargs:
        print('vararg:', value)
    for name, value in sorted(kwargs.items()):
        print('kwarg:', name, value)
*** Test Cases ***
Positional
    Various Args    hello    world                # Logs 'arg: hello' and 'vararg: world'.

Named
    Various Args    arg=value                     # Logs 'arg: value'.

Kwargs
    Various Args    a=1    b=2    c=3             # Logs 'kwarg: a 1', 'kwarg: b 2' and 'kwarg: c 3'.
    Various Args    c=3    a=1    b=2             # Same as above. Order does not matter.

Positional and kwargs
    Various Args    1    2    kw=3                # Logs 'arg: 1', 'vararg: 2' and 'kwarg: kw 3'.

Named and kwargs
    Various Args    arg=value      hello=world    # Logs 'arg: value' and 'kwarg: hello world'.
    Various Args    hello=world    arg=value      # Same as above. Order does not matter.

For a real world example of using a signature exactly like in the above example, see Run Process and Start Keyword keywords in the Process library.
有关使用与上述示例完全相同的签名的真实的示例,请参见Process库中的Run ProcessStart Keyword关键字。

Keyword-only arguments Keyword-only参数

Starting from Robot Framework 3.1, it is possible to use named-only arguments with different keywords. This support is provided by Python's keyword-only arguments. Keyword-only arguments are specified after possible *varargs or after a dedicated * marker when *varargs are not needed. Possible **kwargs are specified after keyword-only arguments.
从Robot Framework 3.1开始,可以使用带有不同关键字的仅命名参数。这种支持由Python的keyword-only参数提供。仅关键字参数在可能的 *varargs之后指定,或者在不需要*varargs时在专用*标记之后指定。可能的 **kwargs在仅关键字参数后指定。

Example: 范例:

def sort_words(*words, case_sensitive=False):
    key = str.lower if case_sensitive else None
    return sorted(words, key=key)

def strip_spaces(word, *, left=True, right=True):
    if left:
        word = word.lstrip()
    if right:
        word = word.rstrip()
    return word
*** Test Cases ***
Example
    Sort Words    Foo    bar    baZ
    Sort Words    Foo    bar    baZ    case_sensitive=True
    Strip Spaces    ${word}    left=False

Positional-only arguments
唯立场论元

Python supports so called positional-only arguments that make it possible to specify that an argument can only be given as a positional argument, not as a named argument like name=value. Positional-only arguments are specified before normal arguments and a special / marker must be used after them:
Python支持所谓的仅位置参数,这使得可以指定参数只能作为位置参数给出,而不是作为命名参数(如name=value)。仅定位参数在普通参数之前指定,并且必须在它们之后使用特殊/标记:

def keyword(posonly, /, normal):
    print(f"Got positional-only argument {posonly} and normal argument {normal}.")

The above keyword could be used like this:
上面的关键字可以这样使用:

*** Test Cases ***
Example
    # Positional-only and normal argument used as positional arguments.
    Keyword    foo    bar
    # Normal argument can also be named.
    Keyword    foo    normal=bar

If a positional-only argument is used with a value that contains an equal sign like example=usage, it is not considered to mean named argument syntax even if the part before the = would match the argument name. This rule only applies if the positional-only argument is used in its correct position without other arguments using the name argument syntax before it, though.
如果仅定位参数与包含等号的值一起使用,如example=用法,则即使=之前的部分与参数名称匹配,也不会被认为是命名参数语法。但是,只有当仅位置参数在其正确位置使用,而其他参数在其之前没有使用name参数语法时,此规则才适用。

*** Test Cases ***
Example
    # Positional-only argument gets literal value `posonly=foo` in this case.
    Keyword    posonly=foo    normal=bar
    # This fails.
    Keyword    normal=bar    posonly=foo

Positional-only arguments are fully supported starting from Robot Framework 4.0. Using them as positional arguments works also with earlier versions, but using them as named arguments causes an error on Python side.
从Robot Framework 4.0开始完全支持仅位置参数。使用它们作为位置参数也适用于早期版本,但使用它们作为命名参数会导致Python端的错误。

Argument conversion 变元转换

Arguments defined in Robot Framework test data are, by default, passed to keywords as Unicode strings. There are, however, several ways to use non-string values as well:
默认情况下,Robot Framework测试数据中定义的参数作为Unicode字符串传递给关键字。然而,也有几种使用非字符串值的方法:

Automatic argument conversion based on function annotations, types specified using the @keyword decorator, and argument default values are all new features in Robot Framework 3.1. The Supported conversions section specifies which argument conversion are supported in these cases.
基于函数注释的自动参数转换,使用@关键字装饰器指定的类型,以及参数默认值都是Robot Framework 3.1中的新功能。支持的转换部分指定在这些情况下支持哪些参数转换。

Prior to Robot Framework 4.0, automatic conversion was done only if the given argument was a string. Nowadays it is done regardless the argument type.
在Robot Framework 4.0之前,只有当给定的参数是字符串时才执行自动转换。如今,无论参数类型如何,它都可以完成。

Manual argument conversion
手动参数转换

If no type information is specified to Robot Framework, all arguments not passed as variables are given to keywords as Unicode strings. This includes cases like this:
如果没有为Robot Framework指定类型信息,则所有未作为变量传递的参数都将作为Unicode字符串提供给关键字。这包括以下情况:

*** Test Cases ***
Example
    Example Keyword    42    False

It is always possible to convert arguments passed as strings insider keywords. In simple cases this means using int() or float() to convert arguments to numbers, but other kind of conversion is possible as well. When working with Boolean values, care must be taken because all non-empty strings, including string False, are considered true by Python. Robot Framework's own robot.utils.is_truthy() utility handles this nicely as it considers strings like FALSE, NO and NONE (case-insensitively) to be false:
总是可以转换作为字符串内部关键字传递的参数。在简单的情况下,这意味着使用int()float()将参数转换为数字,但其他类型的转换也是可能的。当使用布尔值时,必须小心,因为所有非空字符串,包括字符串False,都被Python认为是true。Robot Framework自己的robot.utils.is_truthy()实用程序很好地处理了这一点,因为它认为字符串如“否”,“”和“无”(不区分大小写)是假的:

from robot.utils import is_truthy


def example_keyword(count, case_insensitive):
    count = int(count)
    if is_truthy(case_insensitive):
        # ...

Keywords can also use Robot Framework's argument conversion functionality via the robot.api.TypeInfo class and its convert method. This can be useful if the needed conversion logic is more complicated or the are needs for better error reporting than what simply using, for example, int() provides.
关键字还可以通过robot.API.TypeInfo类及其convert方法使用Robot Framework的参数转换功能。如果所需的转换逻辑更复杂,或者需要比简单地使用int()提供的更好的错误报告,这可能很有用。

from robot.api import TypeInfo


def example_keyword(count, case_insensitive):
    count = TypeInfo.from_type(int).convert(count)
    if TypeInfo.from_type(bool).convert(case_insensitive):
        # ...

Tip 尖端

It is generally recommended to specify types using type hints or otherwise and let Robot Framework handle argument conversion automatically. Manual argument conversion should only be needed in special cases.
通常建议使用类型提示或其他方式指定类型,并让Robot Framework自动处理参数转换。只有在特殊情况下才需要手动参数转换。

Note 注意

robot.api.TypeInfo is new in Robot Framework 7.0.
robot.API.TypeInfo是Robot Framework 7.0中的新功能。

Specifying argument types using function annotations
使用函数注释检查参数类型

Starting from Robot Framework 3.1, arguments passed to keywords are automatically converted if argument type information is available and the type is recognized. The most natural way to specify types is using Python function annotations. For example, the keyword in the previous example could be implemented as follows and arguments would be converted automatically:
从Robot Framework 3.1开始,如果参数类型信息可用并且类型被识别,则传递给关键字的参数将自动转换。指定类型最自然的方法是使用Python函数注释。例如,上一个示例中的关键字可以如下实现,参数将自动转换:

def example_keyword(count: int, case_insensitive: bool = True):
    if case_insensitive:
        # ...

See the Supported conversions section below for a list of types that are automatically converted and what values these types accept. It is an error if an argument having one of the supported types is given a value that cannot be converted. Annotating only some of the arguments is fine.
有关自动转换的类型以及这些类型接受的值的列表,请参见下面的支持的转换部分。如果具有受支持类型之一的参数被赋予无法转换的值,则会出错。只注释部分参数是可以的。

Annotating arguments with other than the supported types is not an error, and it is also possible to use annotations for other than typing purposes. In those cases no conversion is done, but annotations are nevertheless shown in the documentation generated by Libdoc.
使用不受支持的类型来注释参数不是错误的,也可以将注释用于除类型之外的目的。在这些情况下,不进行转换,但注释仍然显示在Libdoc生成的文档中。

Keywords can also have a return type annotation specified using the -> notation at the end of the signature like def example() -> int:. This information is not used for anything during execution, but starting from Robot Framework 7.0 it is shown by Libdoc for documentation purposes.
关键字也可以在签名末尾使用->表示法指定返回类型注释,如def example()-> int:。此信息在执行期间不用于任何用途,但从Robot Framework 7.0开始,Libdoc会出于文档目的显示此信息。

Specifying argument types using @keyword decorator
使用@keyworddecorator删除参数类型

An alternative way to specify explicit argument types is using the @keyword decorator. Starting from Robot Framework 3.1, it accepts an optional types argument that can be used to specify argument types either as a dictionary mapping argument names to types or as a list mapping arguments to types based on position. These approaches are shown below implementing the same keyword as in earlier examples:
指定显式参数类型的另一种方法是使用@关键字装饰器。从Robot Framework 3.1开始,它接受一个可选的类型参数,该参数可用于指定参数类型,或者作为字典将参数名称映射到类型,或者作为基于位置将参数映射到类型的列表。这些方法如下所示,实现了与前面示例中相同的关键字:

from robot.api.deco import keyword


@keyword(types={'count': int, 'case_insensitive': bool})
def example_keyword(count, case_insensitive=True):
    if case_insensitive:
        # ...

@keyword(types=[int, bool])
def example_keyword(count, case_insensitive=True):
    if case_insensitive:
        # ...

Regardless of the approach that is used, it is not necessarily to specify types for all arguments. When specifying types as a list, it is possible to use None to mark that a certain argument does not have type information and arguments at the end can be omitted altogether. For example, both of these keywords specify the type only for the second argument:
无论使用哪种方法,都不必为所有参数指定类型。当将类型指定为列表时,可以使用None来标记某个参数没有类型信息,并且可以完全省略末尾的参数。例如,这两个关键字都只指定第二个参数的类型:

@keyword(types={'second': float})
def example1(first, second, third):
    # ...

@keyword(types=[None, float])
def example2(first, second, third):
    # ...

Starting from Robot Framework 7.0, it is possible to specify the keyword return type by using key 'return' with an appropriate type in the type dictionary. This information is not used for anything during execution, but it is shown by Libdoc for documentation purposes.
从Robot Framework 7.0开始,可以通过在类型字典中使用具有适当类型的键“return”来指定关键字返回类型。这些信息在执行过程中不用于任何用途,但Libdoc会出于文档目的显示这些信息。

If any types are specified using the @keyword decorator, type information got from annotations is ignored with that keyword. Setting types to None like @keyword(types=None) disables type conversion altogether so that also type information got from default values is ignored.
如果使用@keyword装饰器指定了任何类型,则使用该关键字忽略从注释获得的类型信息。将types设置为None(如@keyword(types=None))会完全禁用类型转换,这样从默认值获取的类型信息也会被忽略。

Implicit argument types based on default values
基于默认值的隐式参数类型

If type information is not got explicitly using annotations or the @keyword decorator, Robot Framework 3.1 and newer tries to get it based on possible argument default value. In this example count and case_insensitive get types int and bool, respectively:
如果类型信息没有使用注释或@关键字装饰器显式获取,Robot Framework 3.1和更新版本会尝试基于可能的参数默认值获取它。在这个例子中,countcase_insensitiveget类型分别是intbool

def example_keyword(count=-1, case_insensitive=True):
    if case_insensitive:
        # ...

When type information is got implicitly based on the default values, argument conversion itself is not as strict as when the information is got explicitly:
当基于默认值隐式获取类型信息时,参数转换本身并不像显式获取信息时那么严格:

  • Conversion may be attempted also to other "similar" types. For example, if converting to an integer fails, float conversion is attempted.
    也可以尝试转换为其他“类似”类型。例如,如果转换为整数失败,则尝试浮点转换。
  • Conversion failures are not errors, keywords get the original value in these cases instead.
    转换失败不是错误,关键字在这些情况下会获得原始值。

If an argument has an explicit type and a default value, conversion is first attempted based on the explicit type. If that fails, then conversion is attempted based on the default value. In this special case conversion based on the default value is strict and a conversion failure causes an error.
如果参数具有显式类型和默认值,则首先根据显式类型尝试转换。如果失败,则尝试基于默认值进行转换。在这种特殊情况下,基于默认值的转换是严格的,转换失败会导致错误。

If argument conversion based on default values is not desired, the whole argument conversion can be disabled with the @keyword decorator like @keyword(types=None).
如果不需要基于默认值的参数转换,可以使用@keyword装饰器(如@keyword(types=None))禁用整个参数转换。

Note 注意

Prior to Robot Framework 4.0 conversion was done based on the default value only if the argument did not have an explict type.
在Robot Framework 4.0之前,只有当参数没有显式类型时,才根据默认值进行转换。

Supported conversions 支持的转换

The table below lists the types that Robot Framework 3.1 and newer convert arguments to. These characteristics apply to all conversions:
下表列出了Robot Framework 3.1和更新版本将参数转换为的类型。这些特征适用于所有转换:

  • Type can be explicitly specified using function annotations or the @keyword decorator.
    类型可以使用函数注释@关键字装饰器显式指定。
  • If not explicitly specified, type can be got implicitly from argument default values.
    如果没有显式指定,type可以从参数默认值隐式获取。
  • Conversion is done regardless of the type of the given argument. If the argument type is incompatible with the expected type, conversion fails.
    无论给定参数的类型如何,都会进行转换。如果参数类型与预期类型不兼容,转换将失败。
  • Conversion failures cause an error if the type has been specified explicitly. If the type is got based on a default value, the given argument is used as-is.
    如果已显式指定类型,则转换失败将导致错误。如果类型是基于默认值获取的,则给定的参数按原样使用。

Note 注意

If an argument has both a type hint and a default value, conversion is first attempted based on the type hint and then, if that fails, based on the default value type. This behavior is likely to change in the future so that conversion based on the default value is done only if the argument does not have a type hint. That will change conversion behavior in cases like arg: list = None where None conversion will not be attempted anymore. Library creators are strongly recommended to specify the default value type explicitly like arg: list | None = None already now.
如果参数同时具有类型提示和默认值,则首先根据类型提示尝试转换,如果失败,则根据默认值类型尝试转换。这种行为将来可能会改变,只有当参数没有类型提示时,才会根据默认值进行转换。这将改变转换行为,例如arg:list = None,其中不再尝试None转换。强烈建议库创建者像arg:list那样显式地指定默认值类型|无=目前无。

The type to use can be specified either using concrete types (e.g. list), by using abstract base classes (ABC) (e.g. Sequence), or by using sub classes of these types (e.g. MutableSequence). Also types in in the typing module that map to the supported concrete types or ABCs (e.g. List) are supported. In all these cases the argument is converted to the concrete type.
要使用的类型可以使用具体类型(例如列表)、抽象基类(ABC)(例如序列)或这些类型的子类(例如MutableSequence)来指定。也支持类型模块中映射到支持的具体类型或ABC(例如List)的类型。在所有这些情况下,参数都被转换为具体类型。

In addition to using the actual types (e.g. int), it is possible to specify the type using type names as a string (e.g. 'int') and some types also have aliases (e.g. 'integer'). Matching types to names and aliases is case-insensitive.
除了使用实际类型(例如int)之外,还可以使用类型名称作为字符串(例如'int')来指定类型,并且某些类型还具有别名(例如'integer')。将类型与名称和别名进行匹配不区分大小写。

The Accepts column specifies which given argument types are converted. If the given argument already has the expected type, no conversion is done. Other types cause conversion failures.
Accepts列指定要转换的给定参数类型。如果给定的参数已经具有预期的类型,则不进行转换。其他类型会导致转换失败。

Supported argument conversions
支持的参数转换
Type 类型 ABC Aliases 别名 Accepts 接受 Explanation 解释 Examples 示例
bool   boolean 布尔 str, int, float, None
StringintfloatNone

Strings TRUE, YES, ON and 1 are converted to True, the empty string as well as FALSE, NO, OFF and 0 are converted to False, and the string NONE is converted to None. Other strings and other accepted values are passed as-is, allowing keywords to handle them specially if needed. All string comparisons are case-insensitive.
字符串TRUEYESON1被转换为True,空字符串以及NULLNOOFF0被转换为False,字符串NONE被转换为None。其他字符串和其他接受的值按原样传递,允许关键字在需要时对其进行特殊处理。所有字符串比较都不区分大小写。

True and false strings can be localized. See the Translations appendix for supported translations.
True和False字符串可以本地化。有关支持的翻译,请参见翻译附录。

TRUE (converted to True)
True(转换为True
off (converted to False)
关闭(转换为False
example (used as-is)
示例(按原样使用)
int Integral 积分 integer, long 整数,长 str, float
字符串浮动

Conversion is done using the int built-in function. Floats are accepted only if they can be represented as integers exactly. For example, 1.0 is accepted and 1.1 is not. If converting a string to an integer fails and the type is got implicitly based on a default value, conversion to float is attempted as well.
使用int内置函数进行转换。只有当浮点数可以精确地表示为整数时,它们才被接受。例如,1.0可以接受,1.1不能接受。如果将字符串转换为整数失败,并且类型是基于默认值隐式获取的,则也会尝试转换为float。

Starting from Robot Framework 4.1, it is possible to use hexadecimal, octal and binary numbers by prefixing values with 0x, 0o and 0b, respectively.
从Robot Framework 4.1开始,可以使用十六进制,八进制和二进制数字,分别使用0x0o0b作为前缀。

Starting from Robot Framework 4.1, spaces and underscores can be used as visual separators for digit grouping purposes.
从Robot Framework 4.1开始,空格和下划线可以用作数字分组的可视分隔符。

Starting from Robot Framework 7.0, strings representing floats are accepted as long as their decimal part is zero. This includes using the scientific notation like 1e100.
从Robot Framework 7.0开始,表示浮点数的字符串只要其小数部分为零就可以接受。这包括使用科学计数法,如1e100

42
-1
10 000 000
1e100
0xFF
0o777
0b1010
0xBAD_C0FFEE
${1}
${1.0}
float 浮子 Real 真实的 double  str, Real
字符串真实的

Conversion is done using the float built-in.
转换是使用内置的浮点数完成的。

Starting from Robot Framework 4.1, spaces and underscores can be used as visual separators for digit grouping purposes.
从Robot Framework 4.1开始,空格和下划线可以用作数字分组的可视分隔符。

3.14
2.9979e8
10 000.000 01
10_000.000_01
Decimal 小数     str, int, float
Stringintfloat

Conversion is done using the Decimal class. Decimal is recommended over float when decimal numbers need to be represented exactly.
转换是使用Decoration类完成的。当十进制数需要精确表示时,建议使用十进制而不是浮点数

Starting from Robot Framework 4.1, spaces and underscores can be used as visual separators for digit grouping purposes.
从Robot Framework 4.1开始,空格和下划线可以用作数字分组的可视分隔符。

3.14
10 000.000 01
10_000.000_01
str   string, unicode 字符串,unicode Any 任何

All arguments are converted to Unicode strings.
所有参数都转换为Unicode字符串。

New in Robot Framework 4.0.
机器人框架4.0中的新功能。

 
bytes 字节     str, bytearray
字符串字节数组
Strings are converted to bytes so that each Unicode code point below 256 is directly mapped to a matching byte. Higher code points are not allowed.
字符串被转换为字节,因此每个低于256的Unicode码位都被直接映射到一个匹配的字节。不允许更高的代码点。
good
hyvä (converted to hyv\xe4)
hyvä(转换为hyv\xe4
\x00 (the null byte)
\x00(空字节)
bytearray     str, bytes
字符串字节
Same conversion as with bytes, but the result is a bytearray.
bytes相同的转换,但结果是bytearray
 
datetime     str, int, float
字符串intfloat

Strings are expected to be timestamps in ISO 8601 like format YYYY-MM-DD hh:mm:ss.mmmmmm, where any non-digit character can be used as a separator or separators can be omitted altogether. Additionally, only the date part is mandatory, all possibly missing time components are considered to be zeros.
ISO 8601中,字符串应该是时间戳,如YYYY-MM-DD hh:mm:ss.mmmmmm格式,其中任何非数字字符都可以用作分隔符或完全省略分隔符。此外,只有日期部分是强制性的,所有可能丢失的时间部分都被认为是零。

Integers and floats are considered to represent seconds since the Unix epoch.
整数和浮点数被认为是自Unix时代以来的秒数。

2022-02-09T16:39:43.632269
2022-02-09 16:39
2022-02-09
${1644417583.632269} (Epoch time)
${1644417583.632269}(纪元时间)
date 日期     str Same string conversion as with datetime, but all time components are expected to be omitted or to be zeros.
datetime相同的字符串转换,但所有时间组件都应被省略或为零。
2018-09-12
timedelta     str, int, float
字符串intfloat
Strings are expected to represent a time interval in one of the time formats Robot Framework supports: time as number, time as time string or time as "timer" string. Integers and floats are considered to be seconds.
字符串预计将以Robot框架支持的一种时间格式表示时间间隔:时间作为数字时间作为时间字符串时间作为“计时器”字符串。整数和浮点数被认为是秒。
42 (42 seconds)
42(42秒)
1 minute 2 seconds
01:02 (same as above)
01:02(同上)
Path 路径 PathLike   str

Strings are converted to pathlib.Path objects. On Windows / is converted to \ automatically.
字符串被转换为pathlib.Path对象。在Windows上,/会自动转换为\

New in Robot Framework 6.0.
机器人框架6.0中的新功能。

/tmp/absolute/path
relative/path/to/file.ext
name.txt
Enum     str

The specified type must be an enumeration (a subclass of Enum or Flag) and given arguments must match its member names.
指定的类型必须是枚举(EnumFlag的子类),并且给定的参数必须与其成员名称匹配。

Matching member names is case, space, underscore and hyphen insensitive, but exact matches have precedence over normalized matches. Ignoring hyphens is new in Robot Framework 7.0.
匹配成员名称不区分大小写、空格、下划线和连字符,但精确匹配优先于规范化匹配。忽略连字符是Robot Framework 7.0中的新功能。

Enumeration documentation and members are shown in documentation generated by Libdoc automatically.
枚举文档和成员显示在Libdoc自动生成的文档中。

class Direction(Enum):
    """Move direction."""
    NORTH = auto()
    NORTH_WEST = auto()

def kw(arg: Direction):
    ...
NORTH (Direction.NORTH)
(方向.北)
north west (Direction.NORTH_WEST)
西北(方向.NORTH_WEST)
IntEnum     str, int
Stringint

The specified type must be an integer based enumeration (a subclass of IntEnum or IntFlag) and given arguments must match its member names or values.
指定的类型必须是基于整数的枚举(IntEnumIntFlag的子类),并且给定的参数必须与其成员名称或值匹配。

Matching member names works the same way as with Enum. Values can be given as integers and as strings that can be converted to integers.
匹配成员名称的工作方式与Enum相同。值可以作为整数和可以转换为整数的字符串给出。

Enumeration documentation and members are shown in documentation generated by Libdoc automatically.
枚举文档和成员显示在Libdoc自动生成的文档中。

New in Robot Framework 4.1.
机器人框架4.1中的新功能。

class PowerState(IntEnum):
    """Turn system ON or OFF."""
    OFF = 0
    ON = 1

def kw(arg: PowerState):
    ...
OFF (PowerState.OFF)
关闭(电源状态关闭)
1 (PowerState.ON)
1(PowerState.ON)
Literal 字面     Any 任何

Only specified values are accepted. Values can be strings, integers, bytes, Booleans, enums and None, and used arguments are converted using the value type specific conversion logic.
仅接受指定的值。值可以是字符串、整数、字节、布尔值、枚举和None,使用的参数使用值类型特定的转换逻辑进行转换。

Strings are case, space, underscore and hyphen insensitive, but exact matches have precedence over normalized matches.
字符串不区分大小写、空格、下划线和连字符,但精确匹配优先于规范化匹配。

Literal provides similar functionality as Enum, but does not support custom documentation.
Literal提供与Enum类似的功能,但不支持自定义文档。

New in Robot Framework 7.0.
机器人框架7.0中的新功能。

def kw(arg: Literal['ON', 'OFF']):
    ...
OFF
on
None 没有一     str String NONE (case-insensitive) is converted to the Python None object. Other values cause an error.
字符串NONE(不区分大小写)转换为PythonNone对象。其他值会导致错误。
None
Any 任何     Any 任何

Any value is accepted. No conversion is done.
任何值都可以接受。不进行转换。

New in Robot Framework 6.1.
机器人框架6.1中的新功能。

 
list 列表 Sequence 序列 sequence 序列 str, Sequence
字符串序列

Strings must be Python list literals. They are converted to actual lists using the ast.literal_eval function. They can contain any values ast.literal_eval supports, including lists and other containers.
字符串必须是Python列表文字。使用ast.literal_eval函数将它们转换为实际的列表。它们可以包含ast.literal_eval支持的任何值,包括列表和其他容器。

If the used type hint is list (e.g. arg: list), sequences that are not lists are converted to lists. If the type hint is generic Sequence, sequences are used without conversion.
如果使用的类型提示是列表(例如arg:list),则不是列表的序列将被转换为列表。如果类型提示为泛型Sequence,则使用序列而不进行转换。

Alias sequence is new in Robot Framework 7.0.
机器人框架7.0中的新序列

['one', 'two']
[('one', 1), ('two', 2)]
tuple 元组     str, Sequence
字符串序列
Same as list, but string arguments must tuple literals.
list相同,但字符串参数必须元组化。
('one', 'two')
set 设置 Set 设置   str, Container
字符串容器
Same as list, but string arguments must be set literals or set() to create an empty set.
list相同,但字符串参数必须是set字面量或set()以创建空集。
{1, 2, 3, 42}
set()
frozenset     str, Container
字符串容器
Same as set, but the result is a frozenset.
set相同,但结果是frozenset
{1, 2, 3, 42}
frozenset()
dict Mapping 映射 dictionary, mapping, map 字典,映射,地图 str, Mapping
字符串映射

Same as list, but string arguments must be dictionary literals.
list相同,但字符串参数必须是字典字面量。

Alias mapping is new in Robot Framework 7.0.
Robot Framework 7.0中的新特性是映射

{'a': 1, 'b': 2}
{'key': 1, 'nested': {'key': 2}}
TypedDict     str, Mapping
字符串映射

Same as dict, but dictionary items are also converted to the specified types and items not included in the type spec are not allowed.
dict相同,但字典项也被转换为指定的类型,并且不允许类型规范中不包含的项。

New in Robot Framework 6.0. Normal dict conversion was used earlier.
机器人框架6.0中的新功能。前面使用了正常的dict转换。

class Config(TypedDict):
    width: int
    enabled: bool
{'width': 1600, 'enabled': True}

Note 注意

Starting from Robot Framework 5.0, types that have a converted are automatically shown in Libdoc outputs.
从Robot Framework 5.0开始,已转换的类型会自动显示在Libdoc输出中。

Note 注意

Prior to Robot Framework 4.0, most types supported converting string NONE (case-insensitively) to Python None. That support has been removed and None conversion is only done if an argument has None as an explicit type or as a default value.
在Robot Framework 4.0之前,大多数类型都支持将字符串NONE(不区分大小写)转换为PythonNone。该支持已被删除,只有当参数将None作为显式类型或默认值时,才执行None转换。

Specifying multiple possible types
搜索多种可能的类型

Starting from Robot Framework 4.0, it is possible to specify that an argument has multiple possible types. In this situation argument conversion is attempted based on each type and the whole conversion fails if none of these conversions succeed.
从Robot Framework 4.0开始,可以指定参数具有多种可能的类型。在这种情况下,将尝试基于每个类型进行参数转换,如果这些转换都不成功,则整个转换将失败。

When using function annotations, the natural syntax to specify that an argument has multiple possible types is using Union:
当使用函数注释时,指定参数具有多个可能类型的自然语法是使用Union

from typing import Union


def example(length: Union[int, float], padding: Union[int, str, None] = None):
    ...

When using Python 3.10 or newer, it is possible to use the native type1 | type2 syntax instead:
当使用Python 3.10或更高版本时,可以使用原生类型1| type 2语法:

def example(length: int | float, padding: int | str | None = None):
    ...

Robot Framework 7.0 enhanced the support for the union syntax so that also "stringly typed" unions like 'type1 | type2' work. This syntax works also with older Python versions:
Robot Framework 7.0增强了对union语法的支持,因此也可以使用“字符串类型”的union,如“type 1|类型2工作。此语法也适用于较旧的Python版本:

def example(length: 'int | float', padding: 'int | str | None' = None):
    ...

An alternative is specifying types as a tuple. It is not recommended with annotations, because that syntax is not supported by other tools, but it works well with the @keyword decorator:
另一种方法是将类型指定为元组。不推荐使用注释,因为其他工具不支持这种语法,但它可以很好地与@keyword装饰器一起使用:

from robot.api.deco import keyword


@keyword(types={'length': (int, float), 'padding': (int, str, None)})
def example(length, padding=None):
    ...

With the above examples the length argument would first be converted to an integer and if that fails then to a float. The padding would be first converted to an integer, then to a string, and finally to None.
在上面的例子中,长度参数首先会被转换为整数,如果转换失败,则转换为浮点数。填充将首先转换为整数,然后转换为字符串,最后转换为None

If the given argument has one of the accepted types, then no conversion is done and the argument is used as-is. For example, if the length argument gets value 1.5 as a float, it would not be converted to an integer. Notice that using non-string values like floats as an argument requires using variables as these examples giving different values to the length argument demonstrate:
如果给定的参数具有可接受的类型之一,则不进行转换,并按原样使用该参数。例如,如果length参数的值为1.5,则它不会被转换为整数。请注意,使用非字符串值(如浮点数)作为参数需要使用变量,因为这些示例为长度参数提供了不同的值:

*** Test Cases ***
Conversion
    Example    10        # Argument is a string. Converted to an integer.
    Example    1.5       # Argument is a string. Converted to a float.
    Example    ${10}     # Argument is an integer. Accepted as-is.
    Example    ${1.5}    # Argument is a float. Accepted as-is.

If one of the accepted types is string, then no conversion is done if the given argument is a string. As the following examples giving different values to the padding argument demonstrate, also in these cases passing other types is possible using variables:
如果接受的类型之一是字符串,那么如果给定的参数是字符串,则不进行转换。正如下面的例子给padding参数提供不同的值所展示的,在这些情况下,也可以使用变量传递其他类型:

*** Test Cases ***
Conversion
    Example    1    big        # Argument is a string. Accepted as-is.
    Example    1    10         # Argument is a string. Accepted as-is.
    Example    1    ${10}      # Argument is an integer. Accepted as-is.
    Example    1    ${None}    # Argument is `None`. Accepted as-is.
    Example    1    ${1.5}     # Argument is a float. Converted to an integer.

If the given argument does not have any of the accepted types, conversion is attempted in the order types are specified. If any conversion succeeds, the resulting value is used without attempting remaining conversions. If no individual conversion succeeds, the whole conversion fails.
如果给定的参数没有任何可接受的类型,则将按照指定类型的顺序尝试转换。如果任何转换成功,则使用结果值,而不尝试其余的转换。如果没有单个转换成功,则整个转换失败。

If a specified type is not recognized by Robot Framework, then the original argument value is used as-is. For example, with this keyword conversion would first be attempted to an integer, but if that fails the keyword would get the original argument:
如果Robot Framework无法识别指定的类型,则按原样使用原始参数值。例如,使用此关键字,首先将尝试转换为整数,但如果失败,关键字将获得原始参数:

def example(argument: Union[int, Unrecognized]):
    ...

Starting from Robot Framework 6.1, the above logic works also if an unrecognized type is listed before a recognized type like Union[Unrecognized, int]. Also in this case int conversion is attempted, and the argument id passed as-is if it fails. With earlier Robot Framework versions, int conversion would not be attempted at all.
从Robot Framework 6.1开始,如果未识别的类型列在已识别的类型(如Union[Unrecognized,int])之前,则上述逻辑也有效。同样在这种情况下,尝试int转换,如果失败,则按原样传递参数id。在早期的Robot Framework版本中,根本不会尝试int转换。

Type conversion with generics
使用泛型进行类型转换

With generics also the parameterized syntax like list[int] or dict[str, int] works. When this syntax is used, the given value is first converted to the base type and then individual items are converted to the nested types. Conversion with different generic types works according to these rules:
对于泛型,参数化语法如list[int]dict[str,int]也可以工作。使用此语法时,给定值首先转换为基类型,然后将各个项转换为嵌套类型。不同泛型类型的转换根据以下规则进行:

  • With lists there can be only one type like list[float]. All list items are converted to that type.
    对于列表,只能有一种类型,比如list[float]。所有列表项都转换为该类型。
  • With tuples there can be any number of types like tuple[int, int] and tuple[str, int, bool]. Tuples used as arguments are expected to have exactly that amount of items and they are converted to matching types.
    对于元组,可以有任意数量的类型,例如tuple[int,int]tuple[str,int,bool]。作为参数使用的元组应该具有相同数量的项,并且它们被转换为匹配的类型。
  • To create a homogeneous tuple, it is possible to use exactly one type and ellipsis like tuple[int, ...]. In this case tuple can have any number of items and they are all converted to the specified type.
    要创建一个同构元组,可以只使用一种类型和省略号,如tuple[int,.] .在这种情况下,tuple可以有任意数量的项目,它们都被转换为指定的类型。
  • With dictionaries there must be exactly two types like dict[str, int]. Dictionary keys are converted using the former type and values using the latter.
    对于字典,必须有两种类型,如dict[str,int]。字典键使用前者类型进行转换,值使用后者进行转换。
  • With sets there can be exactly one type like set[float]. Conversion logic is the same as with lists.
    对于集合,可以只有一种类型,比如set[float]。转换逻辑与列表相同。

Using the native list[int] syntax requires Python 3.9 or newer. If there is a need to support also earlier Python versions, it is possible to either use matching types from the typing module like List[int] or use the "stringly typed" syntax like 'list[int]'.
使用本机list [int]语法需要Python 3.9或更高版本。如果还需要支持早期的Python版本,可以使用类型模块中的匹配类型(如List [int])或使用"字符串类型"语法(如'list [int]')。

Note 注意

Support for converting nested types with generics is new in Robot Framework 6.0. Same syntax works also with earlier versions, but arguments are only converted to the base type and nested types are not used for anything.
Robot Framework 6.0中新增了对使用泛型转换嵌套类型的支持。相同的语法也适用于早期版本,但参数仅转换为基类型,而嵌套类型不用于任何内容。

Note 注意

Support for "stringly typed" parameterized generics is new in Robot Framework 7.0.
Robot Framework 7.0中新增了对"字符串类型"参数化泛型的支持。

Custom argument converters
自定义参数转换器

In addition to doing argument conversion automatically as explained in the previous sections, Robot Framework supports custom argument conversion. This functionality has two main use cases:
除了如前几节所述自动执行参数转换外,Robot Framework还支持自定义参数转换。此功能有两个主要用例:

  • Overriding the standard argument converters provided by the framework.
    重写框架提供的标准参数转换器。
  • Adding argument conversion for custom types and for other types not supported out-of-the-box.
    为自定义类型和不支持的其他类型添加参数转换。

Argument converters are functions or other callables that get arguments used in data and convert them to desired format before arguments are passed to keywords. Converters are registered for libraries by setting ROBOT_LIBRARY_CONVERTERS attribute (case-sensitive) to a dictionary mapping desired types to converts. When implementing a library as a module, this attribute must be set on the module level, and with class based libraries it must be a class attribute. With libraries implemented as classes, it is also possible to use the converters argument with the @library decorator. Both of these approaches are illustrated by examples in the following sections.
参数转换器是获取数据中使用的参数并在将参数传递给关键字之前将其转换为所需格式的函数或其他可调用项。通过将ROBOT_LIBRARY_CONVERTERS属性(区分大小写)设置为将所需类型映射到转换的字典,可以为库注册转换器。当将库实现为模块时,此属性必须在模块级别上设置,并且对于基于类的库,它必须是类属性。对于实现为类的库,也可以使用带有@library装饰器converters参数。这两种方法都将在以下各节中通过示例进行说明。

Note 注意

Custom argument converters are new in Robot Framework 5.0.
自定义参数转换器是Robot Framework 5.0中的新功能。

Overriding default converters
覆盖默认转换器

Let's assume we wanted to create a keyword that accepts date objects for users in Finland where the commonly used date format is dd.mm.yyyy. The usage could look something like this:
让我们假设我们想要创建一个关键字,它接受芬兰用户的日期对象,芬兰用户常用的日期格式是dd.mm.yyyy。用法可能是这样的:

*** Test Cases ***
Example
    Keyword    25.1.2022

Automatic argument conversion supports dates, but it expects them to be in yyyy-mm-dd format so it will not work. A solution is creating a custom converter and registering it to handle date conversion:
自动参数转换支持日期,但它要求日期为yyyy-mm-dd格式,因此无法工作。一个解决方案是创建一个自定义转换器并注册它来处理日期转换:

from datetime import date


# Converter function.
def parse_fi_date(value):
    day, month, year = value.split('.')
    return date(int(year), int(month), int(day))


# Register converter function for the specified type.
ROBOT_LIBRARY_CONVERTERS = {date: parse_fi_date}


# Keyword using custom converter. Converter is resolved based on argument type.
def keyword(arg: date):
    print(f'year: {arg.year}, month: {arg.month}, day: {arg.day}')
Conversion errors 转换错误

If we try using the above keyword with invalid argument like invalid, it fails with this error:
如果我们尝试使用上面的关键字与无效参数,如invalid,它会失败,并出现以下错误:

ValueError: Argument 'arg' got value 'invalid' that cannot be converted to date: not enough values to unpack (expected 3, got 1)

This error is not too informative and does not tell anything about the expected format. Robot Framework cannot provide more information automatically, but the converter itself can be enhanced to validate the input. If the input is invalid, the converter should raise a ValueError with an appropriate message. In this particular case there would be several ways to validate the input, but using regular expressions makes it possible to validate both that the input has dots (.) in correct places and that date parts contain correct amount of digits:
此错误信息量不太大,也没有说明预期格式的任何信息。Robot Framework无法自动提供更多信息,但可以增强转换器本身以验证输入。如果输入无效,转换器应该引发一个ValueError,并给出相应的消息。在这种特殊情况下,有几种方法可以验证输入,但是使用正则表达式可以验证输入是否有点(. ),并且日期部分包含正确数量的数字:

from datetime import date
import re


def parse_fi_date(value):
    # Validate input using regular expression and raise ValueError if not valid.
    match = re.match(r'(\d{1,2})\.(\d{1,2})\.(\d{4})$', value)
    if not match:
        raise ValueError(f"Expected date in format 'dd.mm.yyyy', got '{value}'.")
    day, month, year = match.groups()
    return date(int(year), int(month), int(day))


ROBOT_LIBRARY_CONVERTERS = {date: parse_fi_date}


def keyword(arg: date):
    print(f'year: {arg.year}, month: {arg.month}, day: {arg.day}')

With the above converter code, using the keyword with argument invalid fails with a lot more helpful error message:
使用上面的转换器代码,使用带参数invalid的关键字会失败,并显示更多有用的错误消息:

ValueError: Argument 'arg' got value 'invalid' that cannot be converted to date: Expected date in format 'dd.mm.yyyy', got 'invalid'.
Restricting value types 限制值类型

By default Robot Framework tries to use converters with all given arguments regardless their type. This means that if the earlier example keyword would be used with a variable containing something else than a string, conversion code would fail in the re.match call. For example, trying to use it with argument ${42} would fail like this:
默认情况下,Robot Framework尝试使用具有所有给定参数的转换器,而不管它们的类型。这意味着,如果前面的example关键字用于包含字符串以外内容的变量,则转换代码将在re.match调用中失败。例如,尝试将它与参数${42}一起使用会失败,如下所示:

ValueError: Argument 'arg' got value '42' (integer) that cannot be converted to date: TypeError: expected string or bytes-like object

This error situation could naturally handled in the converter code by checking the value type, but if the converter only accepts certain types, it is typically easier to just restrict the value to that type. Doing it requires only adding appropriate type hint to the converter:
这种错误情况可以通过检查值类型在转换器代码中自然处理,但如果转换器只接受某些类型,则通常更容易将值限制为该类型。这样做只需要向转换器添加适当的类型提示:

def parse_fi_date(value: str):
     # ...

Notice that this type hint is not used for converting the value before calling the converter, it is used for strictly restricting which types can be used. With the above addition calling the keyword with ${42} would fail like this:
请注意,此类型提示不是用于在调用转换器之前转换值,而是用于严格限制可以使用哪些类型。使用上面的添加,使用${42}调用关键字将失败,如下所示:

ValueError: Argument 'arg' got value '42' (integer) that cannot be converted to date.

If the converter can accept multiple types, it is possible to specify types as a Union. For example, if we wanted to enhance our keyword to accept also integers so that they would be considered seconds since the Unix epoch, we could change the converter like this:
如果转换器可以接受多个类型,则可以将类型指定为Union。例如,如果我们想增强我们的关键字,使其也接受整数,以便将它们视为自Unix纪元以来的秒数,我们可以这样更改转换器:

from datetime import date
import re
from typing import Union


# Accept both strings and integers.
def parse_fi_date(value: Union[str, int]):
    # Integers are converted separately.
    if isinstance(value, int):
        return date.fromtimestamp(value)
    match = re.match(r'(\d{1,2})\.(\d{1,2})\.(\d{4})$', value)
    if not match:
        raise ValueError(f"Expected date in format 'dd.mm.yyyy', got '{value}'.")
    day, month, year = match.groups()
    return date(int(year), int(month), int(day))


ROBOT_LIBRARY_CONVERTERS = {date: parse_fi_date}


def keyword(arg: date):
    print(f'year: {arg.year}, month: {arg.month}, day: {arg.day}')
Converting custom types 转换自定义类型

A problem with the earlier example is that date objects could only be given in dd.mm.yyyy format. It would not work if there was a need to support dates in different formats like in this example:
前面的例子的一个问题是日期对象只能以dd.mm.yyyy格式给出。如果需要支持不同格式的日期,它将不起作用,如本例所示:

*** Test Cases ***
Example
    Finnish     25.1.2022
    US          1/25/2022
    ISO 8601    2022-01-22

A solution to this problem is creating custom types instead of overriding the default date conversion:
这个问题的解决方案是创建自定义类型,而不是覆盖默认的日期转换:

from datetime import date
import re
from typing import Union

from robot.api.deco import keyword, library


# Custom type. Extends an existing type but that is not required.
class FiDate(date):

    # Converter function implemented as a classmethod. It could be a normal
    # function as well, but this way all code is in the same class.
    @classmethod
    def from_string(cls, value: str):
        match = re.match(r'(\d{1,2})\.(\d{1,2})\.(\d{4})$', value)
        if not match:
            raise ValueError(f"Expected date in format 'dd.mm.yyyy', got '{value}'.")
        day, month, year = match.groups()
        return cls(int(year), int(month), int(day))


# Another custom type.
class UsDate(date):

    @classmethod
    def from_string(cls, value: str):
        match = re.match(r'(\d{1,2})/(\d{1,2})/(\d{4})$', value)
        if not match:
            raise ValueError(f"Expected date in format 'mm/dd/yyyy', got '{value}'.")
        month, day, year = match.groups()
        return cls(int(year), int(month), int(day))


# Register converters using '@library' decorator.
@library(converters={FiDate: FiDate.from_string, UsDate: UsDate.from_string})
class Library:

    # Uses custom converter supporting 'dd.mm.yyyy' format.
    @keyword
    def finnish(self, arg: FiDate):
        print(f'year: {arg.year}, month: {arg.month}, day: {arg.day}')

    # Uses custom converter supporting 'mm/dd/yyyy' format.
    @keyword
    def us(self, arg: UsDate):
        print(f'year: {arg.year}, month: {arg.month}, day: {arg.day}')

    # Uses IS0-8601 compatible default conversion.
    @keyword
    def iso_8601(self, arg: date):
        print(f'year: {arg.year}, month: {arg.month}, day: {arg.day}')

    # Accepts date in different formats.
    @keyword
    def any(self, arg: Union[FiDate, UsDate, date]):
        print(f'year: {arg.year}, month: {arg.month}, day: {arg.day}')
Strict type validation 严格类型验证

Converters are not used at all if the argument is of the specified type to begin with. It is thus easy to enable strict type validation with a custom converter that does not accept any value. For example, the Example keyword accepts only StrictType instances:
如果参数是指定的开始类型,则根本不使用转换器。因此,很容易使用不接受任何值的自定义转换器启用严格的类型验证。例如,Example关键字仅接受BottType实例:

class StrictType:
    pass


def strict_converter(arg):
    raise TypeError(f'Only StrictType instances accepted, got {type(arg).__name__}.')


ROBOT_LIBRARY_CONVERTERS = {StrictType: strict_converter}


def example(argument: StrictType):
    assert isinstance(argument, StrictType)

As a convenience, Robot Framework allows setting converter to None to get the same effect. For example, this code behaves exactly the same way as the code above:
为了方便起见,Robot Framework允许将转换器设置为None以获得相同的效果。例如,这段代码的行为与上面的代码完全相同:

class StrictType:
    pass


ROBOT_LIBRARY_CONVERTERS = {StrictType: None}


def example(argument: StrictType):
    assert isinstance(argument, StrictType)

Note 注意

Using None as a strict converter is new in Robot Framework 6.0. An explicit converter function needs to be used with earlier versions.
使用None作为严格转换器是Robot Framework 6.0中的新功能。显式转换器函数需要与早期版本一起使用。

Accessing the test library from converter
从转换器中删除测试库

Starting from Robot Framework 6.1, it is possible to access the library instance from a converter function. This allows defining dynamic type conversions that depend on the library state. For example, if the library can be configured to test particular locale, you might use the library state to determine how a date should be parsed like this:
从Robot Framework 6.1开始,可以从转换器函数访问库实例。这允许定义依赖于库状态的动态类型转换。例如,如果库可以配置为测试特定的语言环境,则可以使用库状态来确定应该如何解析日期,如下所示:

from datetime import date
import re


def parse_date(value, library):
    # Validate input using regular expression and raise ValueError if not valid.
    # Use locale based from library state to determine parsing format.
    if library.locale == 'en_US':
        match = re.match(r'(?P<month>\d{1,2})/(?P<day>\d{1,2})/(?P<year>\d{4})$', value)
        format = 'mm/dd/yyyy'
    else:
        match = re.match(r'(?P<day>\d{1,2})\.(?P<month>\d{1,2})\.(?P<year>\d{4})$', value)
        format = 'dd.mm.yyyy'
    if not match:
        raise ValueError(f"Expected date in format '{format}', got '{value}'.")
    return date(int(match.group('year')), int(match.group('month')), int(match.group('day')))


ROBOT_LIBRARY_CONVERTERS = {date: parse_date}


def keyword(arg: date):
    print(f'year: {arg.year}, month: {arg.month}, day: {arg.day}')

The library argument to converter function is optional, i.e. if the converter function only accepts one argument, the library argument is omitted. Similar result can be achieved by making the converter function accept only variadic arguments, e.g. def parse_date(*varargs).
转换器函数的参数是可选的,即如果转换器函数只接受一个参数,则省略参数。类似的结果可以通过使转换器函数只接受可变参数来实现,例如def parse_date(*varargs)

Converter documentation 转换器文档

Information about converters is added to outputs produced by Libdoc automatically. This information includes the name of the type, accepted values (if specified using type hints) and documentation. Type information is automatically linked to all keywords using these types.
有关转换器的信息会自动添加到Libdoc生成的输出中。这些信息包括类型的名称、可接受的值(如果使用类型提示指定)和文档。类型信息自动链接到使用这些类型的所有关键字。

Used documentation is got from the converter function by default. If it does not have any documentation, documentation is got from the type. Both of these approaches to add documentation to converters in the previous example thus produce the same result:
默认情况下,使用的文档是从转换器函数中获取的。如果它没有任何文档,则从类型中获取文档。在前面的示例中,这两种向转换器添加文档的方法产生了相同的结果:

class FiDate(date):

    @classmethod
    def from_string(cls, value: str):
        """Date in ``dd.mm.yyyy`` format."""
        # ...


class UsDate(date):
    """Date in ``mm/dd/yyyy`` format."""

    @classmethod
    def from_string(cls, value: str):
        # ...

Adding documentation is in general recommended to provide users more information about conversion. It is especially important to document converter functions registered for existing types, because their own documentation is likely not very useful in this context.
通常建议添加文档,以便为用户提供有关转换的更多信息。为现有类型注册的转换器函数编写文档尤其重要,因为它们自己的文档在这种情况下可能不是很有用。

@keyword decorator
@keyworddecorator

Although Robot Framework gets lot of information about keywords automatically, such as their names and arguments, there are sometimes needs to configure this information further. This is typically easiest done by using the robot.api.deco.keyword decorator. It has several useful usages that are explained thoroughly elsewhere and only listened here as a reference:
虽然Robot Framework自动获取有关关键字的大量信息,例如它们的名称和参数,但有时需要进一步配置这些信息。这通常最容易通过使用robot.API.deco.关键字装饰器来完成。它有几个有用的用法,在其他地方有详细的解释,在这里只作为参考:

@not_keyword decorator
@not_keyword装饰器

The robot.api.deco.not_keyword decorator can be used for disabling functions or methods becoming keywords.
robot.API.deco.not_keyword装饰器可用于禁止函数或方法成为关键字

Using custom decorators 使用自定义装饰器

When implementing keywords, it is sometimes useful to modify them with Python decorators. However, decorators often modify function signatures and can thus confuse Robot Framework's introspection when determining which arguments keywords accept. This is especially problematic when creating library documentation with Libdoc and when using external tools like RIDE. The easiest way to avoid this problem is decorating the decorator itself using functools.wraps. Other solutions include using external modules like decorator and wrapt that allow creating fully signature-preserving decorators.
在实现关键字时,使用Python装饰器修改它们有时很有用。然而,装饰器经常修改函数签名,因此在确定关键字接受哪些参数时可能会混淆Robot Framework的内省。在使用Libdoc创建库文档以及使用外部工具(如RIDE)时,这一点尤其成问题。避免这个问题的最简单的方法是使用functools.wraps装饰装饰器本身。其他解决方案包括使用外部模块,如decoratorwrapt,允许创建完全保留签名的装饰器。

Note 注意

Support for "unwrapping" decorators decorated with functools.wraps is a new feature in Robot Framework 3.2.
支持用functools.wraps装饰的“展开”装饰器是Robot Framework 3.2中的一个新特性。

Embedding arguments into keyword names
将参数嵌入关键字名称

Library keywords can also accept embedded arguments the same way as user keywords. This section mainly covers the Python syntax to use to create such keywords, the embedded arguments syntax itself is covered in detail as part of user keyword documentation.
库关键字也可以像用户关键字一样接受嵌入参数。本节主要介绍用于创建此类关键字的Python语法,嵌入式参数语法本身作为用户关键字文档的一部分详细介绍。

Library keywords with embedded arguments need to have a custom name that is typically set using the @keyword decorator. Values matching embedded arguments are passed to the function or method implementing the keyword as positional arguments. If the function or method accepts more arguments, they can be passed to the keyword as normal positional or named arguments. Argument names do not need to match the embedded argument names, but that is generally a good convention.
带有嵌入参数的库关键字需要有一个自定义名称,通常使用@keyword装饰器设置。与嵌入参数匹配的值将作为位置参数传递给实现关键字的函数或方法。如果函数或方法接受更多参数,则可以将它们作为普通的位置参数或命名参数传递给关键字。参数名不需要与嵌入的参数名匹配,但这通常是一个很好的约定。

Keywords accepting embedded arguments:
接受嵌入参数的关键词:

from robot.api.deco import keyword


@keyword('Select ${animal} from list')
def select_animal_from_list(animal):
    ...


@keyword('Number of ${animals} should be')
def number_of_animals_should_be(animals, count):
    ...

Tests using the above keywords:
使用上述关键字进行测试:

*** Test Cases ***
Embedded arguments
    Select cat from list
    Select dog from list

Embedded and normal arguments
    Number of cats should be    2
    Number of dogs should be    count=3

If type information is specified, automatic argument conversion works also with embedded arguments:
如果指定了类型信息,则自动参数转换也适用于嵌入参数:

@keyword('Add ${quantity} copies of ${item} to cart')
def add_copies_to_cart(quantity: int, item: str):
    ...

Note 注意

Support for mixing embedded arguments and normal arguments is new in Robot Framework 7.0.
Robot Framework 7.0中新增了对混合嵌入参数和普通参数的支持。

Asynchronous keywords 异步关键字

Starting from Robot Framework 6.1, it is possible to run native asynchronous functions (created by async def) just like normal functions:
从Robot Framework 6.1开始,可以像运行普通函数一样运行本地异步函数(由Apache def创建):

import asyncio
from robot.api.deco import keyword


@keyword
async def this_keyword_waits():
    await asyncio.sleep(5)

You can get the reference of the loop using asyncio.get_running_loop() or asyncio.get_event_loop(). Be careful when modifying how the loop runs, it is a global resource. For example, never call loop.close() because it will make it impossible to run any further coroutines. If you have any function or resource that requires the event loop, even though await is not used explicitly, you have to define your function as async to have the event loop available.
你可以使用juncio.get_running_loop()juncio.get_event_loop()来获取循环的引用。当修改循环的运行方式时要小心,它是一个全局资源。例如,永远不要调用loop.close(),因为这将使它无法运行任何进一步的协程。如果你有任何需要事件循环的函数或资源,即使没有显式使用await,你也必须将函数定义为javaC以使事件循环可用。

More examples of functionality:
更多功能示例:

import asyncio
from robot.api.deco import keyword


async def task_async():
    await asyncio.sleep(5)

@keyword
async def examples():
    tasks = [task_async() for _ in range(10)]
    results = await asyncio.gather(*tasks)

    background_task = asyncio.create_task(task_async())
    await background_task

    # If running with Python 3.10 or higher
    async with asyncio.TaskGroup() as tg:
        task1 = tg.create_task(task_async())
        task2 = tg.create_task(task_async())

Note 注意

Robot Framework waits for the function to complete. If you want to have a task that runs for a long time, use, for example, asyncio.create_task(). It is your responsibility to manage the task and save a reference to avoid it being garbage collected. If the event loop closes and a task is still pending, a message will be printed to the console.
Robot Framework等待函数完成。如果你想让一个任务运行很长时间,可以使用,例如,Pencio.create_task()。您有责任管理任务并保存引用以避免其被垃圾收集。如果事件循环关闭,而任务仍处于挂起状态,则会将一条消息打印到控制台。

Note 注意

If execution of keyword cannot continue for some reason, for example a signal stop, Robot Framework will cancel the async task and any of its children. Other async tasks will continue running normally.
如果关键字的执行由于某种原因而无法继续,例如信号停止,Robot Framework将取消BLOG任务及其任何子任务。其他的dsp任务将继续正常运行。

4.1.4   Communicating with Robot Framework
4.1.4与机器人框架通信

After a method implementing a keyword is called, it can use any mechanism to communicate with the system under test. It can then also send messages to Robot Framework's log file, return information that can be saved to variables and, most importantly, report if the keyword passed or not.
在调用实现关键字的方法之后,它可以使用任何机制与被测系统进行通信。然后,它还可以向Robot Framework的日志文件发送消息,返回可以保存到变量的信息,最重要的是,报告关键字是否通过。

Reporting keyword status 报告关键字状态

Reporting keyword status is done simply using exceptions. If an executed method raises an exception, the keyword status is FAIL, and if it returns normally, the status is PASS.
报告关键字状态只需使用异常即可完成。如果执行的方法引发异常,则关键字status为FAIL,如果正常返回,则状态为PASS

Normal execution failures and errors can be reported using the standard exceptions such as AssertionError, ValueError and RuntimeError. There are, however, some special cases explained in the subsequent sections where special exceptions are needed.
正常的执行失败和错误可以使用标准异常报告,如AssertionErrorValueErrorRuntimeError。然而,在随后的章节中解释了一些需要特殊例外的特殊情况。

Error messages 错误消息

The error message shown in logs, reports and the console is created from the exception type and its message. With generic exceptions (for example, AssertionError, Exception, and RuntimeError), only the exception message is used, and with others, the message is created in the format ExceptionType: Actual message.
日志、报告和控制台中显示的错误消息是根据异常类型及其消息创建的。对于一般异常(例如,AssertionErrorExceptionRuntimeError),只使用异常消息,对于其他异常,消息以ExceptionType:Actual消息的格式创建。

It is possible to avoid adding the exception type as a prefix to failure message also with non generic exceptions. This is done by adding a special ROBOT_SUPPRESS_NAME attribute with value True to your exception.
对于非通用异常,可以避免将异常类型作为前缀添加到失败消息中。这是通过向异常添加一个值为True的特殊ROBOT_SUPPRESS_NAME属性来完成的。

Python: 蟒蛇皮:

class MyError(RuntimeError):
    ROBOT_SUPPRESS_NAME = True

In all cases, it is important for the users that the exception message is as informative as possible.
在所有情况下,异常消息尽可能提供信息对用户来说都很重要。

HTML in error messages 错误消息中的HTML

It is also possible to have HTML formatted error messages by starting the message with text *HTML*:
也可以通过以文本*HTML*开始消息来获得HTML格式的错误消息:

raise AssertionError("*HTML* <a href='robotframework.org'>Robot Framework</a> rulez!!")

This method can be used both when raising an exception in a library, like in the example above, and when users provide an error message in the test data.
当在库中引发异常时(如上面的示例),以及当用户在测试数据中提供错误消息时,都可以使用此方法。

Cutting long messages automatically
自动剪切长消息

If the error message is longer than 40 lines, it will be automatically cut from the middle to prevent reports from getting too long and difficult to read. The full error message is always shown in the log message of the failed keyword.
如果错误消息超过40行,它将自动从中间剪切,以防止报告变得太长而难以阅读。完整的错误消息始终显示在failed关键字的日志消息中。

Tracebacks 回迹

The traceback of the exception is also logged using DEBUG log level. These messages are not visible in log files by default because they are very rarely interesting for normal users. When developing libraries, it is often a good idea to run tests using --loglevel DEBUG.
异常的追溯也使用DEBUG日志级别记录。默认情况下,这些消息在日志文件中不可见,因为普通用户很少会对它们感兴趣。开发库时,使用--loglevel DEBUG运行测试通常是个好主意。

Exceptions provided by Robot Framework
由Robot Framework提供

Robot Framework provides some exceptions that libraries can use for reporting failures and other events. These exceptions are exposed via the robot.api package and contain the following:
Robot Framework提供了一些库可以用于报告失败和其他事件的例外。这些异常通过robot.API包公开,包含以下内容:

Failure
Report failed validation. There is no practical difference in using this exception compared to using the standard AssertionError. The main benefit of using this exception is that its name is consistent with other provided exceptions.
报告验证失败。与使用标准AssertionError相比,使用此异常没有实际区别。使用此异常的主要好处是它的名称与其他提供的异常一致。
Error
Report error in execution. Failures related to the system not behaving as expected should typically be reported using the Failure exception or the standard AssertionError. This exception can be used, for example, if the keyword is used incorrectly. There is no practical difference, other than consistent naming with other provided exceptions, compared to using this exception and the standard RuntimeError.
报告执行错误。与系统未按预期运行相关的故障通常应使用Failure异常或标准AssertionError来报告。例如,如果关键字使用不正确,则可以使用此异常。与使用此异常和标准RuntimeError相比,除了与其他提供的异常保持一致的命名之外,没有实际的区别。
ContinuableFailure
Report failed validation but allow continuing execution. See the Continuable failures section below for more information.
报告验证失败,但允许继续执行。有关详细信息,请参阅下面的“可持续故障”部分。
SkipExecution
Mark the executed test or task skipped. See the Skipping tests section below for more information.
标记已执行的测试或跳过的任务。有关详细信息,请参阅下面的跳过测试部分。
FatalError
Report error that stops the whole execution. See the Stopping test execution section below for more information.
停止整个执行的报告错误。有关详细信息,请参阅下面的停止测试执行部分。

Note 注意

All these exceptions are new in Robot Framework 4.0. Other features than skipping tests, which is also new in Robot Framework 4.0, are available by other means in earlier versions.
所有这些异常都是Robot Framework 4.0中的新特性。除了跳过测试之外,其他功能也是Robot Framework 4.0中的新功能,在早期版本中可以通过其他方式使用。

Continuable failures 连续故障

It is possible to continue test execution even when there are failures. The easiest way to do that is using the provided robot.api.ContinuableFailure exception:
即使出现故障,也可以继续执行测试。最简单的方法是使用提供robot.API.ContinuableFailure异常:

from robot.api import ContinuableFailure


def example_keyword():
    if something_is_wrong():
        raise ContinuableFailure('Something is wrong but execution can continue.')
    ...

An alternative is creating a custom exception that has a special ROBOT_CONTINUE_ON_FAILURE attribute set to a True value. This is demonstrated by the example below.
另一种方法是创建一个自定义异常,该异常具有设置为True值的特殊ROBOT_CONTINUE_ON_FAILURE属性。下面的例子说明了这一点。

class MyContinuableError(RuntimeError):
    ROBOT_CONTINUE_ON_FAILURE = True

Skipping tests 跳过测试

It is possible to skip tests with a library keyword. The easiest way to do that is using the provided robot.api.SkipExecution exception:
使用库关键字可以跳过测试。最简单的方法是使用提供robot.API.SkipExecution异常:

from robot.api import SkipExecution


def example_keyword():
    if test_should_be_skipped():
        raise SkipExecution('Cannot proceed, skipping test.')
    ...

An alternative is creating a custom exception that has a special ROBOT_SKIP_EXECUTION attribute set to a True value. This is demonstrated by the example below.
另一种方法是创建一个自定义异常,该异常具有设置为True值的特殊ROBOT_SKIP_EXECUTION属性。下面的例子说明了这一点。

class MySkippingError(RuntimeError):
    ROBOT_SKIP_EXECUTION = True

Stopping test execution 停止测试执行

It is possible to fail a test case so that the whole test execution is stopped. The easiest way to accomplish this is using the provided robot.api.FatalError exception:
测试用例可能会失败,从而导致整个测试执行停止。最简单的方法是使用提供robot.API.FatalError异常:

from robot.api import FatalError


def example_keyword():
    if system_is_not_running():
        raise FatalError('System is not running!')
    ...

In addition to using the robot.api.FatalError exception, it is possible create a custom exception that has a special ROBOT_EXIT_ON_FAILURE attribute set to a True value. This is illustrated by the example below.
除了使用robot.API.FatalError异常之外,还可以创建一个自定义异常,该异常具有设置为True值的特殊ROBOT_EXIT_ON_FAILURE属性。下面的例子说明了这一点。

class MyFatalError(RuntimeError):
    ROBOT_EXIT_ON_FAILURE = True

Logging information 测井信息

Exception messages are not the only way to give information to the users. In addition to them, methods can also send messages to log files simply by writing to the standard output stream (stdout) or to the standard error stream (stderr), and they can even use different log levels. Another, and often better, logging possibility is using the programmatic logging APIs.
异常消息并不是向用户提供信息的唯一方式。除此之外,方法还可以通过写入标准输出流(stdout)或标准错误流(stderr)来向日志文件发送消息,它们甚至可以使用不同的日志级别。另一种更好的日志记录方法是使用编程日志API

By default, everything written by a method into the standard output is written to the log file as a single entry with the log level INFO. Messages written into the standard error are handled similarly otherwise, but they are echoed back to the original stderr after the keyword execution has finished. It is thus possible to use the stderr if you need some messages to be visible on the console where tests are executed.
默认情况下,由方法写入标准输出的所有内容都将作为日志级别为INFO的单个条目写入日志文件。写入标准错误的消息将以类似的方式处理,但在关键字执行完成后,它们将回显到原始的stderr。因此,如果您需要在执行测试的控制台上显示某些消息,则可以使用stderr。

Using log levels 使用日志级别

To use other log levels than INFO, or to create several messages, specify the log level explicitly by embedding the level into the message in the format *LEVEL* Actual log message. In this formant *LEVEL* must be in the beginning of a line and LEVEL must be one of the available concrete log levels TRACE, DEBUG, INFO, WARN or ERROR, or a pseudo log level HTML or CONSOLE. The pseudo levels can be used for logging HTML and logging to console, respectively.
要使用INFO以外的其他日志级别,或创建多个消息,请通过以*LEVEL* Actual日志消息格式将级别嵌入消息中来显式指定日志级别。在这个共振峰中,*LEVEL*必须在一行的开头,并且LEVEL必须是可用的具体日志级别TRACEDEBUGINFOWARNERROR之一,或者是伪日志级别HTMLCONSOLE。伪级别可分别用于记录HTML记录到控制台

Errors and warnings 错误和警告

Messages with ERROR or WARN level are automatically written to the console and a separate Test Execution Errors section in the log files. This makes these messages more visible than others and allows using them for reporting important but non-critical problems to users.
带有ERRORWARN级别的消息将自动写入控制台和日志文件中的单独测试执行错误部分。这使得这些消息比其他消息更明显,并允许使用它们向用户报告重要但非关键的问题。

Logging HTML 记录HTML

Everything normally logged by the library will be converted into a format that can be safely represented as HTML. For example, <b>foo</b> will be displayed in the log exactly like that and not as foo. If libraries want to use formatting, links, display images and so on, they can use a special pseudo log level HTML. Robot Framework will write these messages directly into the log with the INFO level, so they can use any HTML syntax they want. Notice that this feature needs to be used with care, because, for example, one badly placed </table> tag can ruin the log file quite badly.
库通常记录的所有内容都将转换为可以安全地表示为HTML的格式。例如,<b>boo</b>将在日志中显示为与此完全相同,而不是foo。如果库想要使用格式化、链接、显示图像等,它们可以使用一个特殊的伪日志级HTML。Robot Framework会将这些消息直接写入INFO级别的日志中,因此它们可以使用任何想要的HTML语法。注意,这个特性需要小心使用,因为,例如,一个错误放置的</table>标记可能会严重破坏日志文件。

When using the public logging API, various logging methods have optional html attribute that can be set to True to enable logging in HTML format.
当使用公共日志记录API时,各种日志记录方法都有可选的html属性,可以将其设置为True以启用HTML格式的日志记录。

Timestamps 时间戳

By default messages logged via the standard output or error streams get their timestamps when the executed keyword ends. This means that the timestamps are not accurate and debugging problems especially with longer running keywords can be problematic.
默认情况下,当executed关键字结束时,通过标准输出或错误流记录的消息将获得其时间戳。这意味着时间戳不准确,调试问题尤其是运行时间较长的关键字可能会出现问题。

Keywords have a possibility to add an accurate timestamp to the messages they log if there is a need. The timestamp must be given as milliseconds since the Unix epoch and it must be placed after the log level separated from it with a colon:
关键字有可能添加一个准确的时间戳,他们记录的消息,如果有必要。时间戳必须以自Unix纪元以来的毫秒为单位,并且必须放置在日志级别之后,用冒号与之分隔:

*INFO:1308435758660* Message with timestamp
*HTML:1308435758661* <b>HTML</b> message with timestamp

As illustrated by the examples below, adding the timestamp is easy. It is, however, even easier to get accurate timestamps using the programmatic logging APIs. A big benefit of adding timestamps explicitly is that this approach works also with the remote library interface.
如下面的例子所示,添加时间戳很容易。然而,使用编程日志API更容易获得准确的时间戳。显式添加时间戳的一大好处是,这种方法也适用于远程库接口

import time


def example_keyword():
    print('*INFO:%d* Message with timestamp' % (time.time()*1000))
Logging to console 登录到控制台

Libraries have several options for writing messages to the console. As already discussed, warnings and all messages written to the standard error stream are written both to the log file and to the console. Both of these options have a limitation that the messages end up to the console only after the currently executing keyword finishes.
库有几个将消息写入控制台的选项。如前所述,写入标准错误流的警告和所有消息都将写入日志文件和控制台。这两个选项都有一个限制,即只有在当前执行的关键字完成之后,消息才会到达控制台。

Starting from Robot Framework 6.1, libraries can use a pseudo log level CONSOLE for logging messages both to the log file and to the console:
从Robot Framework 6.1开始,库可以使用伪日志级别CONSOLE将消息记录到日志文件和控制台:

def my_keyword(arg):
    print('*CONSOLE* Message both to log and to console.')

These messages will be logged to the log file using the INFO level similarly as with the HTML pseudo log level. When using this approach, messages are logged to the console only after the keyword execution ends.
这些消息将使用INFO级别记录到日志文件中,与HTML伪日志级别类似。使用此方法时,只有在关键字执行结束后,才会将消息记录到控制台。

Another option is writing messages to sys.__stdout__ or sys.__stderr__. When using this approach, messages are written to the console immediately and are not written to the log file at all:
另一种选择是将消息写入sys.__标准输出__系统__ stderr__.使用此方法时,消息会立即写入控制台,而不会写入日志文件:

import sys


def my_keyword(arg):
    print('Message only to console.', file=sys.__stdout__)

The final option is using the public logging API. Also in with this approach messages are written to the console immediately:
最后一个选项是使用公共日志记录API。在这种方法中,消息也会立即写入控制台:

from robot.api import logger


def log_to_console(arg):
    logger.console('Message only to console.')

def log_to_console_and_log_file(arg):
    logger.info('Message both to log and to console.', also_console=True)
Logging example 日志记录示例

In most cases, the INFO level is adequate. The levels below it, DEBUG and TRACE, are useful for writing debug information. These messages are normally not shown, but they can facilitate debugging possible problems in the library itself. The WARN or ERROR level can be used to make messages more visible and HTML is useful if any kind of formatting is needed. Level CONSOLE can be used when the message needs to shown both in console and in the log file.
在大多数情况下,INFO级别就足够了。它下面的级别DEBUGTRACE对于编写调试信息很有用。这些消息通常不显示,但它们可以帮助调试库本身中可能存在的问题。WARNERROR级别可用于使消息更加可见,如果需要任何类型的格式,则HTML非常有用。当消息需要同时显示在控制台和日志文件中时,可以使用级别CONSOLE

The following examples clarify how logging with different levels works.
以下示例说明了不同级别的日志记录的工作原理。

print('Hello from a library.')
print('*WARN* Warning from a library.')
print('*ERROR* Something unexpected happen that may indicate a problem in the test.')
print('*INFO* Hello again!')
print('This will be part of the previous message.')
print('*INFO* This is a new message.')
print('*INFO* This is <b>normal text</b>.')
print('*CONSOLE* This logs into console and log file.')
print('*HTML* This is <b>bold</b>.')
print('*HTML* <a href="http://robotframework.org">Robot Framework</a>')
16:18:42.123 INFO Hello from a library. 你好,图书馆。
16:18:42.123 WARN Warning from a library. 来自图书馆的警告
16:18:42.123 ERROR Something unexpected happen that may indicate a problem in the test.
一些意想不到的事情发生,可能表明测试中存在问题。
16:18:42.123 INFO Hello again! 又见面了!
This will be part of the previous message.
这将是前一条消息的一部分。
16:18:42.123 INFO This is a new message.
这是一个新的信息。
16:18:42.123 INFO This is <b>normal text</b>.
这是正常的文本
16:18:42.123 INFO This logs into console and log file.
这将登录到控制台和日志文件中。
16:18:42.123 INFO This is bold.
这很大胆
16:18:42.123 INFO Robot Framework

Programmatic logging APIs
编程日志API

Programmatic APIs provide somewhat cleaner way to log information than using the standard output and error streams.
编程API提供了比使用标准输出和错误流更干净的记录信息的方法。

Public logging API 公共日志记录API

Robot Framework has a Python based logging API for writing messages to the log file and to the console. Test libraries can use this API like logger.info('My message') instead of logging through the standard output like print('*INFO* My message'). In addition to a programmatic interface being a lot cleaner to use, this API has a benefit that the log messages have accurate timestamps.
Robot Framework有一个基于Python的日志记录API,用于将消息写入日志文件和控制台。测试库可以使用这个API,比如logger.info(“我的消息”),而不是通过标准输出进行记录,比如print(“* INFO* 我的消息”)。除了编程接口使用起来更简洁之外,这个API还有一个好处,即日志消息具有准确的时间戳

The public logging API is thoroughly documented as part of the API documentation at https://robot-framework.readthedocs.org. Below is a simple usage example:
公共日志记录API作为https://robot-framework.readthedocs.org上的API文档的一部分进行了详细记录。下面是一个简单的使用示例:

from robot.api import logger


def my_keyword(arg):
    logger.debug('Got argument %s' % arg)
    do_something()
    logger.info('<i>This</i> is a boring example', html=True)
    logger.console('Hello, console!')

An obvious limitation is that test libraries using this logging API have a dependency to Robot Framework. If Robot Framework is not running, the messages are redirected automatically to Python's standard logging module.
一个明显的限制是使用此日志记录API的测试库依赖于Robot框架。如果Robot Framework没有运行,消息会自动重定向到Python的标准日志模块。

Using Python's standard logging module
使用Python的标准日志模块

In addition to the new public logging API, Robot Framework offers a built-in support to Python's standard logging module. This works so that all messages that are received by the root logger of the module are automatically propagated to Robot Framework's log file. Also this API produces log messages with accurate timestamps, but logging HTML messages or writing messages to the console are not supported. A big benefit, illustrated also by the simple example below, is that using this logging API creates no dependency to Robot Framework.
除了新的公共日志API,Robot Framework还提供了对Python标准日志模块的内置支持。这使得模块的根日志程序接收到的所有消息都自动传播到Robot Framework的日志文件。此外,此API生成具有准确时间戳的日志消息,但不支持记录HTML消息或将消息写入控制台。一个很大的好处,也说明了下面的简单例子,是使用这个日志API创建没有依赖于机器人框架。

import logging


def my_keyword(arg):
    logging.debug('Got argument %s' % arg)
    do_something()
    logging.info('This is a boring example')

The logging module has slightly different log levels than Robot Framework. Its levels DEBUG, INFO, WARNING and ERROR are mapped directly to the matching Robot Framework log levels, and CRITICAL is mapped to ERROR. Custom log levels are mapped to the closest standard level smaller than the custom level. For example, a level between INFO and WARNING is mapped to Robot Framework's INFO level.
日志模块的日志级别与Robot Framework略有不同。其级别DEBUGINFOCRITICALERROR直接映射到匹配的Robot Framework日志级别,而CRITICAL映射到ERROR。自定义日志级别映射到比自定义级别小的最接近的标准级别。例如,INFOINFO之间的级别映射到Robot Framework的INFO级别。

Logging during library initialization
库初始化期间的日志记录

Libraries can also log during the test library import and initialization. These messages do not appear in the log file like the normal log messages, but are instead written to the syslog. This allows logging any kind of useful debug information about the library initialization. Messages logged using the WARN or ERROR levels are also visible in the test execution errors section in the log file.
库还可以在测试库导入和初始化期间进行日志记录。这些消息不会像普通日志消息那样出现在日志文件中,而是写入系统日志。这允许记录有关库初始化的任何类型的有用调试信息。使用WARNERROR级别记录的消息也可以在日志文件的测试执行错误部分中看到。

Logging during the import and initialization is possible both using the standard output and error streams and the programmatic logging APIs. Both of these are demonstrated below.
在导入和初始化期间,可以使用标准输出和错误流以及编程日志API进行日志记录。这两种情况都在下面得到了证明。

Library logging using the logging API during import:
导入期间使用日志记录API的库日志记录:

from robot.api import logger


logger.debug("Importing library")


def keyword():
    # ...

Note 注意

If you log something during initialization, i.e. in Python __init__, the messages may be logged multiple times depending on the library scope.
如果你在初始化过程中记录了一些东西,例如在Python__init__中,根据库的作用域,这些消息可能会被记录多次。

Returning values 返回值

The final way for keywords to communicate back to the core framework is returning information retrieved from the system under test or generated by some other means. The returned values can be assigned to variables in the test data and then used as inputs for other keywords, even from different test libraries.
关键字与核心框架进行通信的最后一种方式是返回从被测系统中检索到的信息或通过其他方式生成的信息。返回的值可以分配给测试数据中的变量,然后用作其他关键字的输入,甚至来自不同的测试库。

Values are returned using the return statement in methods. Normally, one value is assigned into one scalar variable, as illustrated in the example below. This example also illustrates that it is possible to return any objects and to use extended variable syntax to access object attributes.
在方法中使用return语句返回值。通常,一个值被分配给一个标量变量,如下面的示例所示。这个例子还说明了返回任何对象和使用扩展变量语法来访问对象属性是可能的。

from mymodule import MyObject


def return_string():
    return "Hello, world!"

def return_object(name):
    return MyObject(name)
*** Test Cases ***
Returning one value
    ${string} =    Return String
    Should Be Equal    ${string}    Hello, world!
    ${object} =    Return Object    Robot
    Should Be Equal    ${object.name}    Robot

Keywords can also return values so that they can be assigned into several scalar variables at once, into a list variable, or into scalar variables and a list variable. All these usages require that returned values are lists or list-like objects.
关键字还可以返回值,以便它们可以一次分配到多个标量变量中,分配到列表变量中,或者分配到标量变量和列表变量中。所有这些用法都要求返回值是列表或类似列表的对象。

def return_two_values():
    return 'first value', 'second value'

def return_multiple_values():
    return ['a', 'list', 'of', 'strings']
*** Test Cases ***
Returning multiple values
    ${var1}    ${var2} =    Return Two Values
    Should Be Equal    ${var1}    first value
    Should Be Equal    ${var2}    second value
    @{list} =    Return Two Values
    Should Be Equal    @{list}[0]    first value
    Should Be Equal    @{list}[1]    second value
    ${s1}    ${s2}    @{li} =    Return Multiple Values
    Should Be Equal    ${s1} ${s2}    a list
    Should Be Equal    @{li}[0] @{li}[1]    of strings

Detecting is Robot Framework running
正在检测Robot Framework是否正在运行

Starting from Robot Framework 6.1, it is easy to detect is Robot Framework running at all and is the dry-run mode active by using the robot_running and dry_run_active properties of the BuiltIn library. A relatively common use case is that library initializers may want to avoid doing some work if the library is not used during execution but is initialized, for example, by Libdoc:
从Robot Framework 6.1开始,通过使用BuiltIn库的robot_runningdry_run_active属性,可以很容易地检测Robot Framework是否正在运行,以及空运行模式是否处于活动状态。一个相对常见的用例是,如果库在执行过程中没有使用,而是被初始化,例如Libdoc初始化,则库初始化器可能希望避免做一些工作:

from robot.libraries.BuiltIn import BuiltIn


class MyLibrary:

    def __init__(self):
        builtin = BuiltIn()
        if builtin.robot_running and not builtin.dry_run_active:
            # Do some initialization that only makes sense during real execution.

For more information about using the BuiltIn library as a programmatic API, including another example using robot_running, see the Using BuiltIn library section.
有关将BuiltIn库用作编程API的详细信息(包括另一个使用robot_running的示例),请参阅使用BuiltIn库一节。

Communication when using threads
使用线程时的通信

If a library uses threads, it should generally communicate with the framework only from the main thread. If a worker thread has, for example, a failure to report or something to log, it should pass the information first to the main thread, which can then use exceptions or other mechanisms explained in this section for communication with the framework.
如果一个库使用线程,它通常应该只从主线程与框架通信。例如,如果工作线程有报告失败或要记录的内容,它应该首先将信息传递给主线程,然后主线程可以使用异常或本节中解释的其他机制与框架进行通信。

This is especially important when threads are run on background while other keywords are running. Results of communicating with the framework in that case are undefined and can in the worst case cause a crash or a corrupted output file. If a keyword starts something on background, there should be another keyword that checks the status of the worker thread and reports gathered information accordingly.
当线程在后台运行而其他关键字正在运行时,这一点尤其重要。在这种情况下,与框架通信的结果是未定义的,并且在最坏的情况下可能导致崩溃或损坏的输出文件。如果一个关键字在后台启动了一些东西,那么应该有另一个关键字来检查工作线程的状态并相应地报告收集的信息。

Messages logged by non-main threads using the normal logging methods from programmatic logging APIs are silently ignored.
非主线程使用编程日志API的常规日志方法记录的消息将被忽略。

There is also a BackgroundLogger in separate robotbackgroundlogger project, with a similar API as the standard robot.api.logger. Normal logging methods will ignore messages from other than main thread, but the BackgroundLogger will save the background messages so that they can be later logged to Robot's log.
在单独robotbackgroundlogger项目中也有一个BackgroundLogger,它具有与标准robot.API.logger类似的API。正常的日志记录方法会忽略来自主线程以外的消息,但BackgroundLogger会保存后台消息,以便稍后可以将其记录到Robot的日志中。

4.1.5   Distributing test libraries
4.1.5分发测试库

Documenting libraries 文档库

A test library without documentation about what keywords it contains and what those keywords do is rather useless. To ease maintenance, it is highly recommended that library documentation is included in the source code and generated from it. Basically, that means using docstrings as in the example below.
一个测试库如果没有关于它包含什么关键字以及这些关键字做什么的文档,是相当无用的。为了便于维护,强烈建议将库文档包含在源代码中,并从源代码中生成。基本上,这意味着使用下面示例中的文档字符串

class MyLibrary:
    """This is an example library with some documentation."""

    def keyword_with_short_documentation(self, argument):
        """This keyword has only a short documentation"""
        pass

    def keyword_with_longer_documentation(self):
        """First line of the documentation is here.

        Longer documentation continues here and it can contain
        multiple lines or paragraphs.
        """
        pass

Python has tools for creating an API documentation of a library documented as above. However, outputs from these tools can be slightly technical for some users. Another alternative is using Robot Framework's own documentation tool Libdoc. This tool can create a library documentation from libraries using the static library API, such as the ones above, but it also handles libraries using the dynamic library API and hybrid library API.
Python提供了一些工具,可以为上面描述的库创建API文档。然而,这些工具的输出对某些用户来说可能有点技术性。另一种选择是使用Robot Framework自己的文档工具Libdoc。此工具可以使用静态库API(如上面的那些)从库创建库文档,但它也可以使用动态库API混合库API处理库。

The first logical line of a keyword documentation, until the first empty line, is used for a special purpose and should contain a short overall description of the keyword. It is used as a short documentation by Libdoc (for example, as a tool tip) and also shown in the test logs.
关键字文档的第一个逻辑行(直到第一个空行)用于特殊目的,并且应该包含关键字的简短总体描述。它被Libdoc用作一个简短的文档(例如,作为一个工具提示),也显示在测试日志中。

By default documentation is considered to follow Robot Framework's documentation formatting rules. This simple format allows often used styles like *bold* and _italic_, tables, lists, links, etc. It is possible to use also HTML, plain text and reStructuredText formats. See the Documentation format section for information how to set the format in the library source code and Libdoc chapter for more information about the formats in general.
默认情况下,文档被认为遵循Robot Framework的文档格式规则。这种简单的格式允许经常使用的样式,如* 粗体 *_斜体_,表格,列表,链接等,也可以使用HTML,纯文本和reStructuredText格式。有关如何在库源代码中设置格式的信息,请参阅文档格式部分,有关格式的一般信息,请参阅Libdoc章节。

Note 注意

Prior to Robot Framework 3.1, the short documentation contained only the first physical line of the keyword documentation.
在Robot Framework 3.1之前,短文档只包含关键字documentation的第一个物理行。

Testing libraries 测试库

Any non-trivial test library needs to be thoroughly tested to prevent bugs in them. Of course, this testing should be automated to make it easy to rerun tests when libraries are changed.
任何重要的测试库都需要经过彻底的测试,以防止其中的bug。当然,这个测试应该是自动化的,以便在库发生变化时可以轻松地进行测试。

Python has excellent unit testing tools, and they suite very well for testing libraries. There are no major differences in using them for this purpose compared to using them for some other testing. The developers familiar with these tools do not need to learn anything new, and the developers not familiar with them should learn them anyway.
Python有优秀的单元测试工具,它们非常适合测试库。与将它们用于其他测试相比,将它们用于此目的没有重大差异。熟悉这些工具的开发人员不需要学习任何新的东西,不熟悉它们的开发人员无论如何都应该学习它们。

It is also easy to use Robot Framework itself for testing libraries and that way have actual end-to-end acceptance tests for them. There are plenty of useful keywords in the BuiltIn library for this purpose. One worth mentioning specifically is Run Keyword And Expect Error, which is useful for testing that keywords report errors correctly.
使用Robot Framework本身来测试库也很容易,这样就可以对它们进行实际的端到端验收测试。BuiltIn库中有很多有用的关键字用于此目的。特别值得一提的是Run Keyword And Expect Error,这对于测试关键字是否正确报告错误非常有用。

Whether to use a unit- or acceptance-level testing approach depends on the context. If there is a need to simulate the actual system under test, it is often easier on the unit level. On the other hand, acceptance tests ensure that keywords do work through Robot Framework. If you cannot decide, of course it is possible to use both the approaches.
使用单元级测试方法还是验收级测试方法取决于上下文。如果需要模拟被测的实际系统,通常在单元级别上更容易。另一方面,验收测试确保关键字通过Robot Framework工作。如果你不能决定,当然可以使用两种方法。

Packaging libraries 打包库

After a library is implemented, documented, and tested, it still needs to be distributed to the users. With simple libraries consisting of a single file, it is often enough to ask the users to copy that file somewhere and set the module search path accordingly. More complicated libraries should be packaged to make the installation easier.
在实现、记录和测试库之后,仍然需要将其分发给用户。对于由单个文件组成的简单库,通常要求用户将该文件复制到某个地方并相应地设置模块搜索路径就足够了。应该打包更复杂的库,以使安装更容易。

Since libraries are normal programming code, they can be packaged using normal packaging tools. For information about packaging and distributing Python code see https://packaging.python.org/. When such a package is installed using pip or other tools, it is automatically in the module search path.
由于库是普通的编程代码,因此可以使用普通的打包工具对其进行打包。有关打包和分发Python代码的信息,请参见https://packaging.python.org/。当使用pip或其他工具安装此类软件包时,它会自动出现在模块搜索路径中。

Deprecating keywords 弃用关键字

Sometimes there is a need to replace existing keywords with new ones or remove them altogether. Just informing the users about the change may not always be enough, and it is more efficient to get warnings at runtime. To support that, Robot Framework has a capability to mark keywords deprecated. This makes it easier to find old keywords from the test data and remove or replace them.
有时需要用新的关键字替换现有的关键字或将它们完全删除。仅仅通知用户有关更改可能并不总是足够的,在运行时获得警告更有效。为了支持这一点,Robot Framework有能力将关键字标记为已弃用。这使得从测试数据中找到旧的关键字并删除或替换它们变得更容易。

Keywords can be deprecated by starting their documentation with text *DEPRECATED, case-sensitive, and having a closing * also on the first line of the documentation. For example, *DEPRECATED*, *DEPRECATED.*, and *DEPRECATED in version 1.5.* are all valid markers.
关键字可以通过在文档的第一行以文本*DEPRECATED开始,区分大小写,并在文档的第一行也有一个关闭*来弃用。例如,*DEPRECATED**DEPRECATED.* ,以及 * 在版本1.5中弃用。* 都是有效的标记

When a deprecated keyword is executed, a deprecation warning is logged and the warning is shown also in the console and the Test Execution Errors section in log files. The deprecation warning starts with text Keyword '<name>' is deprecated. and has rest of the short documentation after the deprecation marker, if any, afterwards. For example, if the following keyword is executed, there will be a warning like shown below in the log file.
当执行一个弃用的关键字时,会记录一个弃用警告,该警告也会显示在控制台和日志文件的测试执行错误部分中。弃用警告以文本Keyword '<name>' is deprecated开头。并在弃用标记(如果有的话)之后提供其余的简短文档。例如,如果执行以下关键字,则日志文件中将出现如下所示的警告。

def example_keyword(argument):
    """*DEPRECATED!!* Use keyword `Other Keyword` instead.

    This keyword does something to given ``argument`` and returns results.
    """
    return do_something(argument)
20080911 16:00:22.650 WARN Keyword 'SomeLibrary.Example Keyword' is deprecated. Use keyword `Other Keyword` instead.
不推荐使用关键字“SomeLibrary.Example Keyword”。使用关键字`Other Keyword`代替。

This deprecation system works with most test libraries and also with user keywords.
这个弃用系统适用于大多数测试库,也适用于用户关键字

4.1.6   Dynamic library API
4.1.6动态库API

The dynamic API is in most ways similar to the static API. For example, reporting the keyword status, logging, and returning values works exactly the same way. Most importantly, there are no differences in importing dynamic libraries and using their keywords compared to other libraries. In other words, users do not need to know what APIs their libraries use.
动态API在大多数方面类似于静态API。例如,报告关键字状态、记录和返回值的工作方式完全相同。最重要的是,与其他库相比,在导入动态库和使用其关键字方面没有任何差异。换句话说,用户不需要知道他们的库使用什么API。

Only differences between static and dynamic libraries are how Robot Framework discovers what keywords a library implements, what arguments and documentation these keywords have, and how the keywords are actually executed. With the static API, all this is done using reflection, but dynamic libraries have special methods that are used for these purposes.
静态库和动态库之间的唯一区别是Robot Framework如何发现库实现的关键字,这些关键字具有哪些参数和文档,以及关键字实际上是如何执行的。对于静态API,所有这些都是使用反射完成的,但是动态库有用于这些目的的特殊方法。

One of the benefits of the dynamic API is that you have more flexibility in organizing your library. With the static API, you must have all keywords in one class or module, whereas with the dynamic API, you can, for example, implement each keyword as a separate class. This use case is not so important with Python, though, because its dynamic capabilities and multi-inheritance already give plenty of flexibility, and there is also possibility to use the hybrid library API.
动态API的一个好处是,您可以更灵活地组织库。对于静态API,您必须将所有关键字放在一个类或模块中,而对于动态API,您可以将每个关键字实现为单独的类。不过,对于Python来说,这个用例并不那么重要,因为它的动态功能和多重继承已经提供了足够的灵活性,而且还有可能使用混合库API

Another major use case for the dynamic API is implementing a library so that it works as proxy for an actual library possibly running on some other process or even on another machine. This kind of a proxy library can be very thin, and because keyword names and all other information is got dynamically, there is no need to update the proxy when new keywords are added to the actual library.
动态API的另一个主要用例是实现一个库,以便它作为可能在其他进程甚至另一台机器上运行的实际库的代理。这种代理库可以非常薄,并且因为关键字名称和所有其他信息是动态获取的,所以当新的关键字添加到实际库时,不需要更新代理。

This section explains how the dynamic API works between Robot Framework and dynamic libraries. It does not matter for Robot Framework how these libraries are actually implemented (for example, how calls to the run_keyword method are mapped to a correct keyword implementation), and many different approaches are possible. Python users may also find the PythonLibCore project useful.
本节说明动态API如何在Robot Framework和动态库之间工作。对于Robot框架来说,这些库实际上如何实现并不重要(例如,如何将对run_keyword方法的调用映射到正确的关键字实现),并且可以采用许多不同的方法。Python用户可能也会发现PythonLibCore项目很有用。

Getting keyword names 获取关键字名称

Dynamic libraries tell what keywords they implement with the get_keyword_names method. This method cannot take any arguments, and it must return a list or array of strings containing the names of the keywords that the library implements.
动态库通过get_keyword_names方法来说明它们实现了哪些关键字。此方法不能接受任何参数,并且必须返回包含库实现的关键字名称的字符串列表或数组。

If the returned keyword names contain several words, they can be returned separated with spaces or underscores, or in the camelCase format. For example, ['first keyword', 'second keyword'], ['first_keyword', 'second_keyword'], and ['firstKeyword', 'secondKeyword'] would all be mapped to keywords First Keyword and Second Keyword.
如果返回的关键字名称包含多个单词,则可以用空格或下划线分隔,或者以驼峰格式返回。例如,[“first keyword”,“second keyword”][“first_keyword”,“second_keyword”]和[“firstKeyword”,“secondKeyword”]都将映射到关键字First KeywordSecond Keyword

Dynamic libraries must always have this method. If it is missing, or if calling it fails for some reason, the library is considered a static library.
动态库必须始终具有此方法。如果缺少它,或者由于某种原因调用它失败,则该库被认为是静态库。

Marking methods to expose as keywords
标记要公开为关键字的方法

If a dynamic library should contain both methods which are meant to be keywords and methods which are meant to be private helper methods, it may be wise to mark the keyword methods as such so it is easier to implement get_keyword_names. The robot.api.deco.keyword decorator allows an easy way to do this since it creates a custom 'robot_name' attribute on the decorated method. This allows generating the list of keywords just by checking for the robot_name attribute on every method in the library during get_keyword_names.
如果一个动态库应该包含两个方法,这意味着是关键字和方法,这意味着是私有的助手方法,它可能是明智的标记关键字方法,这样就更容易实现get_keyword_namesrobot.API.deco.关键字装饰器提供了一种简单的方法来实现这一点,因为它在装饰的方法上创建了一个自定义的“robot_name”属性。这允许在get_keyword_names过程中检查库中每个方法的robot_name属性来生成关键字列表。

from robot.api.deco import keyword


class DynamicExample:

    def get_keyword_names(self):
        # Get all attributes and their values from the library.
        attributes = [(name, getattr(self, name)) for name in dir(self)]
        # Filter out attributes that do not have 'robot_name' set.
        keywords = [(name, value) for name, value in attributes
                    if hasattr(value, 'robot_name')]
        # Return value of 'robot_name', if given, or the original 'name'.
        return [value.robot_name or name for name, value in keywords]

    def helper_method(self):
        # ...

    @keyword
    def keyword_method(self):
        # ...

Running keywords 运行关键字

Dynamic libraries have a special run_keyword (alias runKeyword) method for executing their keywords. When a keyword from a dynamic library is used in the test data, Robot Framework uses the run_keyword method to get it executed. This method takes two or three arguments. The first argument is a string containing the name of the keyword to be executed in the same format as returned by get_keyword_names. The second argument is a list of positional arguments given to the keyword in the test data, and the optional third argument is a dictionary containing named arguments. If the third argument is missing, free named arguments and named-only arguments are not supported, and other named arguments are mapped to positional arguments.
动态库有一个特殊的run_keyword(别名runKeyword)方法来执行其关键字。当在测试数据中使用动态库中的关键字时,Robot Framework使用run_keyword方法来执行该关键字。这个方法有两个或三个参数。第一个参数是一个字符串,包含要执行的关键字的名称,格式与get_keyword_names返回的格式相同。第二个参数是测试数据中关键字的位置参数列表,可选的第三个参数是包含命名参数的字典。如果缺少第三个参数,则不支持自由命名参数仅命名参数,其他命名参数将映射到位置参数。

Note 注意

Prior to Robot Framework 3.1, normal named arguments were mapped to positional arguments regardless did run_keyword accept two or three arguments. The third argument only got possible free named arguments.
在Robot Framework 3.1之前,无论run_keyword接受两个还是三个参数,普通命名参数都映射到位置参数。第三个参数只得到可能的自由命名参数。

After getting keyword name and arguments, the library can execute the keyword freely, but it must use the same mechanism to communicate with the framework as static libraries. This means using exceptions for reporting keyword status, logging by writing to the standard output or by using the provided logging APIs, and using the return statement in run_keyword for returning something.
在获得关键字名称和参数之后,库可以自由地执行关键字,但它必须使用与静态库相同的机制与框架进行通信。这意味着使用异常报告关键字状态,通过写入标准输出或使用提供的日志API进行日志记录,并使用run_keyword中的return语句返回某些内容。

Every dynamic library must have both the get_keyword_names and run_keyword methods but rest of the methods in the dynamic API are optional. The example below shows a working, albeit trivial, dynamic library.
每个动态库都必须有get_keyword_namesrun_keyword方法,但动态API中的其他方法是可选的。下面的例子展示了一个可以工作的动态库,尽管它很简单。

class DynamicExample:

    def get_keyword_names(self):
        return ['first keyword', 'second keyword']

    def run_keyword(self, name, args, kwargs):
        print("Running keyword '%s' with positional arguments %s and named arguments %s."
              % (name, args, kwargs))

Getting keyword arguments
获取关键字参数

If a dynamic library only implements the get_keyword_names and run_keyword methods, Robot Framework does not have any information about the arguments that the implemented keywords accept. For example, both First Keyword and Second Keyword in the example above could be used with any arguments. This is problematic, because most real keywords expect a certain number of keywords, and under these circumstances they would need to check the argument counts themselves.
如果动态库仅实现get_keyword_namesrun_keyword方法,则Robot Framework不具有关于所实现的关键字接受的参数的任何信息。例如,上面例子中的第一个关键字第二个关键字都可以与任何参数一起使用。这是有问题的,因为大多数真实的关键字都需要一定数量的关键字,在这种情况下,它们需要自己检查参数计数。

Dynamic libraries can communicate what arguments their keywords expect by using the get_keyword_arguments (alias getKeywordArguments) method. This method gets the name of a keyword as an argument, and it must return a list of strings containing the arguments accepted by that keyword.
动态库可以通过使用get_keyword_arguments(别名getKeywordArguments)方法来传递其关键字所期望的参数。此方法获取关键字的名称作为参数,并且必须返回包含该关键字接受的参数的字符串列表。

Similarly as other keywords, dynamic keywords can require any number of positional arguments, have default values, accept variable number of arguments, accept free named arguments and have named-only arguments. The syntax how to represent all these different variables is derived from how they are specified in Python and explained in the following table.
与其他关键字类似,动态关键字可以要求任意数量的位置参数,具有默认值,接受可变数量的参数,接受自由命名参数和仅命名参数。如何表示所有这些不同变量的语法来自于它们在Python中的指定方式,并在下表中进行了解释。

Representing different arguments with get_keyword_arguments
get_keyword_arguments表示不同的参数
Argument type 参数类型 How to represent 如何表示 Examples 示例
No arguments 没有参数 Empty list. 空名单。
[]
One or more positional argument
一个或多个位置论点
List of strings containing argument names.
包含参数名称的字符串列表。
['argument']
['arg1', 'arg2', 'arg3']
Default values 默认值

Two ways how to represent the argument name and the default value:
有两种方式来表示参数名和默认值:

  • As a string where the name and the default are separated with =.
    作为字符串,其中名称和默认值用=分隔。
  • As a tuple with the name and the default as separate items. New in Robot Framework 3.2.
    作为一个元组,名称和默认值作为单独的项。机器人框架3.2中的新功能。

String with = separator:
=分隔符的字符串:

['name=default']
['a', 'b=1', 'c=2']

Tuple: 元组:

[('name', 'default')]
['a', ('b', 1), ('c', 2)]
Positional-only arguments
唯立场论元
Arguments before the / marker. New in Robot Framework 6.1.
/标记前的参数。机器人框架6.1中的新功能。
['posonly', '/']
['p', 'q', '/', 'normal']
Variable number of arguments (varargs)
变量数量(varargs)
Argument after possible positional arguments has a * prefix
可能的位置参数后的参数具有*前缀
['*varargs']
['argument', '*rest']
['a', 'b=42', '*c']
Named-only arguments 仅命名参数 Arguments after varargs or a lone * if there are no varargs. With or without defaults. Requires run_keyword to support named-only arguments. New in Robot Framework 3.1.
varargs后的参数,如果没有varargs,则为单独的 *。不管有没有默认值。需要run_keyword支持仅命名参数。机器人框架3.1中的新功能。
['*varargs', 'named']
['*', 'named']
['*', 'x', 'y=default']
['a', '*b', ('c', 42)]
Free named arguments (kwargs)
自由命名参数(kwargs)
Last arguments has ** prefix. Requires run_keyword to support free named arguments.
最后一个参数有**前缀。需要run_keyword支持自由命名参数
['**named']
['a', ('b', 42), '**c']
['*varargs', '**kwargs']
['*', 'kwo', '**kws']

When the get_keyword_arguments is used, Robot Framework automatically calculates how many positional arguments the keyword requires and does it support free named arguments or not. If a keyword is used with invalid arguments, an error occurs and run_keyword is not even called.
当使用get_keyword_arguments时,Robot Framework会自动计算关键字需要多少个位置参数,以及它是否支持自由命名参数。如果关键字与无效参数一起使用,则会出现错误,甚至不会调用run_keyword

The actual argument names and default values that are returned are also important. They are needed for named argument support and the Libdoc tool needs them to be able to create a meaningful library documentation.
返回的实际参数名称和默认值也很重要。它们是命名参数支持所必需的,并且Libdoc工具需要它们来创建有意义的库文档。

As explained in the above table, default values can be specified with argument names either as a string like 'name=default' or as a tuple like ('name', 'default'). The main problem with the former syntax is that all default values are considered strings whereas the latter syntax allows using all objects like ('inteter', 1) or ('boolean', True). When using other objects than strings, Robot Framework can do automatic argument conversion based on them.
如上表所述,默认值可以用参数名指定为字符串(如'name=default')或元组(如('name','default'))。前一种语法的主要问题是所有默认值都被认为是字符串,而后一种语法允许使用所有对象,如('inteter',1)('boolean',True)。当使用字符串以外的其他对象时,Robot Framework可以基于它们进行自动参数转换

For consistency reasons, also arguments that do not accept default values can be specified as one item tuples. For example, ['a', 'b=c', '*d'] and [('a',), ('b', 'c'), ('*d',)] are equivalent.
出于一致性原因,不接受默认值的参数也可以指定为一项元组。例如,“a”,“B= c”,“* d”][(“a”,),(“B”,“c”),(“* d”,)]是等价的。

If get_keyword_arguments is missing or returns Python None for a certain keyword, that keyword gets an argument specification accepting all arguments. This automatic argument spec is either [*varargs, **kwargs] or [*varargs], depending does run_keyword support free named arguments or not.
如果get_keyword_arguments丢失或返回PythonNone,则该关键字将获得接受所有参数的参数规范。这个自动参数规范是[*varargs,**kwargs][*varargs],取决于run_keyword是否支持自由命名参数

Note 注意

Support to specify arguments as tuples like ('name', 'default') is new in Robot Framework 3.2. Support for positional-only arguments in dynamic library API is new in Robot Framework 6.1.
Robot Framework 3.2中新增了将参数指定为元组(如('name','default'))的支持。动态库API中对仅位置参数的支持是Robot Framework 6.1中的新增功能。

Getting keyword argument types
获取关键字参数类型

Robot Framework 3.1 introduced support for automatic argument conversion and the dynamic library API supports that as well. The conversion logic works exactly like with static libraries, but how the type information is specified is naturally different.
Robot Framework 3.1引入了对自动参数转换的支持,动态库API也支持这一点。转换逻辑的工作方式与静态库完全相同,但是类型信息的指定方式自然不同。

With dynamic libraries types can be returned using the optional get_keyword_types method (alias getKeywordTypes). It can return types using a list or a dictionary exactly like types can be specified when using the @keyword decorator. Type information can be specified using actual types like int, but especially if a dynamic library gets this information from external systems, using strings like 'int' or 'integer' may be easier. See the Supported conversions section for more information about supported types and how to specify them.
对于动态库,可以使用可选的get_keyword_types方法(别名getKeywordTypes)返回类型。它可以使用列表或字典返回类型,就像使用@关键字装饰器时指定的类型一样。类型信息可以使用实际类型(如int)来指定,但特别是如果动态库从外部系统获取此信息,使用字符串(如'int''integer')可能更容易。有关支持的类型以及如何指定它们的更多信息,请参见支持的转换部分。

Robot Framework does automatic argument conversion also based on the argument default values. Earlier this did not work with the dynamic API because it was possible to specify arguments only as strings. As discussed in the previous section, this was changed in Robot Framework 3.2 and nowadays default values returned like ('example', True) are automatically used for this purpose.
Robot Framework还根据参数默认值进行自动参数转换。在以前,这对于动态API不起作用,因为只能将参数指定为字符串。如前一节所述,这在Robot Framework 3.2中进行了更改,现在返回的默认值(如('example',True))自动用于此目的。

Starting from Robot Framework 7.0, dynamic libraries can also specify the keyword return type by using key 'return' with an appropriate type in the returned type dictionary. This information is not used for anything during execution, but it is shown by Libdoc for documentation purposes.
从Robot Framework 7.0开始,动态库还可以通过在返回类型字典中使用具有适当类型的键“return”来指定关键字返回类型。这些信息在执行过程中不用于任何用途,但Libdoc会出于文档目的显示这些信息。

Getting keyword tags 获取关键字标签

Dynamic libraries can report keyword tags by using the get_keyword_tags method (alias getKeywordTags). It gets a keyword name as an argument, and should return corresponding tags as a list of strings.
动态库可以使用get_keyword_tags方法(别名getKeywordTags)报告关键字标记。它获取一个关键字名称作为参数,并应返回相应的标记作为字符串列表。

Alternatively it is possible to specify tags on the last row of the documentation returned by the get_keyword_documentation method discussed below. This requires starting the last row with Tags: and listing tags after it like Tags: first tag, second, third.
或者,也可以在下面讨论的get_keyword_documentation方法返回的文档的最后一行上指定标记。这需要以Tags:开始最后一行,并在其后列出标签,如Tags:first tag,second,third

Tip 尖端

The get_keyword_tags method is guaranteed to be called before the get_keyword_documentation method. This makes it easy to embed tags into the documentation only if the get_keyword_tags method is not called.
get_keyword_tags方法保证在get_keyword_documentation方法之前被调用。这使得只有在不调用get_keyword_tags方法的情况下才能轻松地将标记嵌入文档。

Getting keyword documentation
获取关键字文档

If dynamic libraries want to provide keyword documentation, they can implement the get_keyword_documentation method (alias getKeywordDocumentation). It takes a keyword name as an argument and, as the method name implies, returns its documentation as a string.
如果动态库想要提供关键字文档,它们可以实现get_keyword_documentation方法(别名getKeywordDocumentation)。它接受一个关键字名称作为参数,并且正如方法名称所暗示的那样,将其文档作为字符串返回。

The returned documentation is used similarly as the keyword documentation string with static libraries. The main use case is getting keywords' documentations into a library documentation generated by Libdoc. Additionally, the first line of the documentation (until the first \n) is shown in test logs.
返回的documentation与静态库中的关键字documentation字符串的用法类似。主要用例是将关键字的文档放入Libdoc生成的库文档中。此外,文档的第一行(直到第一行)显示在测试日志中。

Getting general library documentation
获取常规库文档

The get_keyword_documentation method can also be used for specifying overall library documentation. This documentation is not used when tests are executed, but it can make the documentation generated by Libdoc much better.
get_keyword_documentation方法也可以用于指定整个库文档。执行测试时不使用此文档,但它可以使Libdoc生成的文档更好。

Dynamic libraries can provide both general library documentation and documentation related to taking the library into use. The former is got by calling get_keyword_documentation with special value __intro__, and the latter is got using value __init__. How the documentation is presented is best tested with Libdoc in practice.
动态库可以提供一般的库文档和与使用库相关的文档。前者是通过调用get_keyword_documentation并带有特殊值__intro__获得的,后者是使用值__init__获得的。文档的呈现方式最好在实践中使用Libdoc进行测试。

Dynamic libraries can also specify the general library documentation directly in the code as the docstring of the library class and its __init__ method. If a non-empty documentation is got both directly from the code and from the get_keyword_documentation method, the latter has precedence.
动态库还可以直接在代码中指定通用库文档,作为库类及其__init__方法的文档字符串。如果一个非空的文档是直接从代码和get_keyword_documentation方法中获得的,那么后者优先。

Getting keyword source information
获取关键字源信息

The dynamic API masks the real implementation of keywords from Robot Framework and thus makes it impossible to see where keywords are implemented. This means that editors and other tools utilizing Robot Framework APIs cannot implement features such as go-to-definition. This problem can be solved by implementing yet another optional dynamic method named get_keyword_source (alias getKeywordSource) that returns the source information.
动态API屏蔽了Robot Framework中关键字的真实的实现,因此无法看到关键字在哪里实现。这意味着使用Robot Framework API的编辑器和其他工具无法实现诸如go to definition之类的功能。这个问题可以通过实现另一个名为get_keyword_source(别名getKeywordSource)的可选动态方法来解决,该方法返回源信息。

The return value from the get_keyword_source method must be a string or None if no source information is available. In the simple case it is enough to simply return an absolute path to the file implementing the keyword. If the line number where the keyword implementation starts is known, it can be embedded to the return value like path:lineno. Returning only the line number is possible like :lineno.
get_keyword_source方法的返回值必须是字符串或None(如果没有可用的源信息)。在简单的情况下,只需返回实现关键字的文件的绝对路径即可。如果关键字implementation开始的行号已知,则可以将其嵌入到返回值中,如path:lineno。可以只返回行号,例如:lineno

The source information of the library itself is got automatically from the imported library class the same way as with other library APIs. The library source path is used with all keywords that do not have their own source path defined.
库本身的源信息是自动从导入的库类中获取的,与其他库API的方式相同。库源路径与所有没有定义自己的源路径的关键字一起使用。

Note 注意

Returning source information for keywords is a new feature in Robot Framework 3.2.
返回关键字的源信息是Robot Framework 3.2中的新功能。

Named argument syntax with dynamic libraries
动态库的命名参数语法

Also the dynamic library API supports the named argument syntax. Using the syntax works based on the argument names and default values got from the library using the get_keyword_arguments method.
动态库API也支持命名参数语法。使用语法的工作原理是基于使用get_keyword_arguments方法从库中获得的参数名称和默认值。

If the run_keyword method accepts three arguments, the second argument gets all positional arguments as a list and the last arguments gets all named arguments as a mapping. If it accepts only two arguments, named arguments are mapped to positional arguments. In the latter case, if a keyword has multiple arguments with default values and only some of the latter ones are given, the framework fills the skipped optional arguments based on the default values returned by the get_keyword_arguments method.
如果run_keyword方法接受三个参数,则第二个参数以列表的形式获取所有位置参数,最后一个参数以映射的形式获取所有命名参数。如果它只接受两个参数,则命名参数映射到位置参数。在后一种情况下,如果关键字有多个带有默认值的参数,并且只给出了后面的一些参数,则框架会根据get_keyword_arguments方法返回的默认值填充跳过的可选参数。

Using the named argument syntax with dynamic libraries is illustrated by the following examples. All the examples use a keyword Dynamic that has an argument specification [a, b=d1, c=d2]. The comment on each row shows how run_keyword would be called in these cases if it has two arguments (i.e. signature is name, args) and if it has three arguments (i.e. name, args, kwargs).
下面的示例说明了如何在动态库中使用命名参数语法。所有的例子都使用了一个关键字Dynamic,它有一个参数规范[a,B=d1,c=d2]。每行上的注释显示了在这些情况下,如果它有两个参数(即签名是name,args)以及如果它有三个参数(即name,args,kwargs),则如何调用run_keyword

*** Test Cases ***                  # args          # args, kwargs
Positional only
    Dynamic    x                    # [x]           # [x], {}
    Dynamic    x      y             # [x, y]        # [x, y], {}
    Dynamic    x      y      z      # [x, y, z]     # [x, y, z], {}

Named only
    Dynamic    a=x                  # [x]           # [], {a: x}
    Dynamic    c=z    a=x    b=y    # [x, y, z]     # [], {a: x, b: y, c: z}

Positional and named
    Dynamic    x      b=y           # [x, y]        # [x], {b: y}
    Dynamic    x      y      c=z    # [x, y, z]     # [x, y], {c: z}
    Dynamic    x      b=y    c=z    # [x, y, z]     # [x], {y: b, c: z}

Intermediate missing
    Dynamic    x      c=z           # [x, d1, z]    # [x], {c: z}

Note 注意

Prior to Robot Framework 3.1, all normal named arguments were mapped to positional arguments and the optional kwargs was only used with free named arguments. With the above examples run_keyword was always called like it is nowadays called if it does not support kwargs.
在Robot Framework 3.1之前,所有普通命名参数都映射到位置参数,可选kwargs仅与自由命名参数一起使用。在上面的例子中,如果run_keyword不支持kwargs,它总是像现在一样被调用。

Free named arguments with dynamic libraries
使用动态库释放命名参数

Dynamic libraries can also support free named arguments (**named). A mandatory precondition for this support is that the run_keyword method takes three arguments: the third one will get the free named arguments along with possible other named arguments. These arguments are passed to the keyword as a mapping.
动态库也可以支持自由命名参数**named)。这种支持的一个强制性前提是run_keyword方法接受三个参数:第三个参数将获得自由的命名参数沿着其他可能的命名参数。这些参数作为映射传递给关键字。

What arguments a keyword accepts depends on what get_keyword_arguments returns for it. If the last argument starts with **, that keyword is recognized to accept free named arguments.
关键字接受什么参数取决于get_keyword_arguments为它返回什么。如果最后一个参数以**开头,则该关键字被识别为接受自由命名参数。

Using the free named argument syntax with dynamic libraries is illustrated by the following examples. All the examples use a keyword Dynamic that has an argument specification [a=d1, b=d2, **named]. The comment shows the arguments that the run_keyword method is actually called with.
下面的示例说明了如何在动态库中使用自由命名参数语法。所有示例都使用了一个关键字Dynamic,它有一个参数规范[a=d1,B=d2,**named]。该注释显示了实际调用run_keyword方法时使用的参数。

*** Test Cases ***                  # args, kwargs
No arguments
    Dynamic                         # [], {}

Only positional
    Dynamic    x                    # [x], {}
    Dynamic    x      y             # [x, y], {}

Only free named
    Dynamic    x=1                  # [], {x: 1}
    Dynamic    x=1    y=2    z=3    # [], {x: 1, y: 2, z: 3}

Positional and free named
    Dynamic    x      y=2           # [x], {y: 2}
    Dynamic    x      y=2    z=3    # [x], {y: 2, z: 3}

Positional as named and free named
    Dynamic    a=1    x=1           # [], {a: 1, x: 1}
    Dynamic    b=2    x=1    a=1    # [], {a: 1, b: 2, x: 1}

Note 注意

Prior to Robot Framework 3.1, normal named arguments were mapped to positional arguments but nowadays they are part of the kwargs along with the free named arguments.
在Robot Framework 3.1之前,普通命名参数被映射到位置参数,但现在它们与自由命名参数一起成为kwargs的沿着。

Named-only arguments with dynamic libraries
动态库的仅命名参数

Starting from Robot Framework 3.1, dynamic libraries can have named-only arguments. This requires that the run_keyword method takes three arguments: the third getting the named-only arguments along with the other named arguments.
从Robot Framework 3.1开始,动态库可以有仅命名的参数。这要求run_keyword方法接受三个参数:第三个参数沿着只命名的参数和其他命名参数。

In the argument specification returned by the get_keyword_arguments method named-only arguments are specified after possible variable number of arguments (*varargs) or a lone asterisk (*) if the keyword does not accept varargs. Named-only arguments can have default values, and the order of arguments with and without default values does not matter.
get_keyword_arguments方法返回的参数规范中,只有命名的参数在可能的变量数量(*varargs)或一个单独的星号(*)之后指定,如果关键字不接受varargs。仅命名的参数可以有默认值,并且参数的顺序(有或没有默认值)无关紧要。

Using the named-only argument syntax with dynamic libraries is illustrated by the following examples. All the examples use a keyword Dynamic that has been specified to have argument specification [positional=default, *varargs, named, named2=default, **free]. The comment shows the arguments that the run_keyword method is actually called with.
下面的示例说明了如何在动态库中使用仅命名参数语法。所有示例都使用了一个关键字Dynamic,该关键字已被指定为具有参数规范[position =default,*varargs,named,named2=default,**free]。注释显示了实际调用run_keyword方法时使用的参数。

*** Test Cases ***                                  # args, kwargs
Only named-only
    Dynamic    named=value                          # [], {named: value}
    Dynamic    named=value    named2=2              # [], {named: value, named2: 2}

Named-only with positional and varargs
    Dynamic    argument       named=xxx             # [argument], {named: xxx}
    Dynamic    a1             a2         named=3    # [a1, a2], {named: 3}

Named-only with positional as named
    Dynamic    named=foo      positional=bar        # [], {positional: bar, named: foo}

Named-only with free named
    Dynamic    named=value    foo=bar               # [], {named: value, foo=bar}
    Dynamic    named2=2       third=3    named=1    # [], {named: 1, named2: 2, third: 3}

Summary 总结

All special methods in the dynamic API are listed in the table below. Method names are listed in the underscore format, but their camelCase aliases work exactly the same way.
下表列出了动态API中的所有特殊方法。方法名以下划线格式列出,但它们的camelCase别名的工作方式完全相同。

All special methods in the dynamic API
动态API中的所有特殊方法
Name 名称 Arguments 论点 Purpose 目的
get_keyword_names   Return names of the implemented keywords.
返回实现的关键字的名称。
run_keyword name, arguments, kwargs Execute the specified keyword with given arguments. kwargs is optional.
使用给定的参数执行指定的关键字kwargs是可选的。
get_keyword_arguments name Return keywords' argument specification. Optional method.
返回关键字的参数规范。可选方法。
get_keyword_types name Return keywords' argument type information. Optional method. New in RF 3.1.
返回关键字的参数类型信息。可选方法。RF 3.1中的新功能。
get_keyword_tags name Return keywords' tags. Optional method.
返回关键字的标签。可选方法。
get_keyword_documentation name Return keywords' and library's documentation. Optional method.
返回关键字和库的文档。可选方法。
get_keyword_source name Return keywords' source. Optional method. New in RF 3.2.
返回关键字的来源。可选方法。RF 3.2中的新功能。

A good example of using the dynamic API is Robot Framework's own Remote library.
使用动态API的一个很好的例子是Robot Framework自己的Remote库

Note 注意

Starting from Robot Framework 7.0, dynamic libraries can have asynchronous implementations of their special methods.
从Robot Framework 7.0开始,动态库可以异步实现其特殊方法。

4.1.7   Hybrid library API 4.1.7混合库API

The hybrid library API is, as its name implies, a hybrid between the static API and the dynamic API. Just as with the dynamic API, it is possible to implement a library using the hybrid API only as a class.
顾名思义,混合库API是静态API和动态API的混合。就像使用动态API一样,可以使用混合API仅作为类来实现库。

Getting keyword names 获取关键字名称

Keyword names are got in the exactly same way as with the dynamic API. In practice, the library needs to have the get_keyword_names or getKeywordNames method returning a list of keyword names that the library implements.
关键字名称的获取方式与动态API完全相同。实际上,库需要让get_keyword_namesgetKeywordNames方法返回库实现的关键字名称列表。

Running keywords 运行关键字

In the hybrid API, there is no run_keyword method for executing keywords. Instead, Robot Framework uses reflection to find methods implementing keywords, similarly as with the static API. A library using the hybrid API can either have those methods implemented directly or, more importantly, it can handle them dynamically.
在混合API中,没有用于执行关键字的run_keyword方法。相反,Robot Framework使用反射来查找实现关键字的方法,与静态API类似。使用混合API的库可以直接实现这些方法,更重要的是,它可以动态地处理这些方法。

In Python, it is easy to handle missing methods dynamically with the __getattr__ method. This special method is probably familiar to most Python programmers and they can immediately understand the following example. Others may find it easier to consult Python Reference Manual first.
在Python中,很容易用__getattr__方法动态处理缺少的方法。这个特殊的方法可能对大多数Python程序员都很熟悉,他们可以立即理解下面的例子。其他人可能会发现先查阅Python参考手册更容易。

from somewhere import external_keyword


class HybridExample:

    def get_keyword_names(self):
        return ['my_keyword', 'external_keyword']

    def my_keyword(self, arg):
        print("My Keyword called with '%s'" % arg)

    def __getattr__(self, name):
        if name == 'external_keyword':
            return external_keyword
        raise AttributeError("Non-existing attribute '%s'" % name)

Note that __getattr__ does not execute the actual keyword like run_keyword does with the dynamic API. Instead, it only returns a callable object that is then executed by Robot Framework.
注意,__getattr__不像run_keyword那样执行动态API的实际关键字。相反,它只返回一个可调用对象,然后由Robot Framework执行。

Another point to be noted is that Robot Framework uses the same names that are returned from get_keyword_names for finding the methods implementing them. Thus the names of the methods that are implemented in the class itself must be returned in the same format as they are defined. For example, the library above would not work correctly, if get_keyword_names returned My Keyword instead of my_keyword.
另一点需要注意的是,Robot Framework使用从get_keyword_names返回的相同名称来查找实现它们的方法。因此,在类本身中实现的方法的名称必须以与它们定义的格式相同的格式返回。例如,如果get_keyword_names返回My Keyword而不是my_keyword,则上面的库将无法正常工作。

Getting keyword arguments and documentation
获取关键字参数和文档

When this API is used, Robot Framework uses reflection to find the methods implementing keywords, similarly as with the static API. After getting a reference to the method, it searches for arguments and documentation from it, in the same way as when using the static API. Thus there is no need for special methods for getting arguments and documentation like there is with the dynamic API.
当使用此API时,Robot Framework使用反射来查找实现关键字的方法,与静态API类似。获取对该方法的引用后,它会从中搜索参数和文档,方式与使用静态API时相同。因此,不需要像动态API那样使用特殊的方法来获取参数和文档。

Summary 总结

When implementing a test library, the hybrid API has the same dynamic capabilities as the actual dynamic API. A great benefit with it is that there is no need to have special methods for getting keyword arguments and documentation. It is also often practical that the only real dynamic keywords need to be handled in __getattr__ and others can be implemented directly in the main library class.
在实现测试库时,混合API具有与实际动态API相同的动态功能。它的一个很大的好处是,不需要有特殊的方法来获取关键字参数和文档。实际上,只有真实的动态关键字需要在__getattr__中处理,其他关键字可以直接在主库类中实现。

Because of the clear benefits and equal capabilities, the hybrid API is in most cases a better alternative than the dynamic API. One notable exception is implementing a library as a proxy for an actual library implementation elsewhere, because then the actual keyword must be executed elsewhere and the proxy can only pass forward the keyword name and arguments.
由于明显的优势和同等的功能,混合API在大多数情况下是比动态API更好的选择。一个值得注意的例外是将库实现为其他地方实际库实现的代理,因为这样实际关键字必须在其他地方执行,代理只能传递关键字名称和参数。

A good example of using the hybrid API is Robot Framework's own Telnet library.
使用混合API的一个很好的例子是Robot Framework自己的API库。

4.1.8   Using Robot Framework's internal modules
4.1.8使用Robot Framework的内部模块

Test libraries can use Robot Framework's internal modules, for example, to get information about the executed tests and the settings that are used. This powerful mechanism to communicate with the framework should be used with care, though, because all Robot Framework's APIs are not meant to be used by externally and they might change radically between different framework versions.
例如,测试库可以使用Robot Framework的内部模块来获取有关已执行的测试和所使用的设置的信息。不过,这种与框架进行通信的强大机制应该小心使用,因为所有Robot Framework的API都不应该被外部使用,并且它们可能会在不同的框架版本之间发生根本性的变化。

Available APIs 可用api

API documentation is hosted separately at the excellent Read the Docs service. If you are unsure how to use certain API or is using them forward compatible, please send a question to mailing list.
API文档单独托管在优秀的Read the Reader服务中。如果您不确定如何使用某些API或正在使用它们向前兼容,请发送问题到邮件列表

Using BuiltIn library 使用内置库

The safest API to use are methods implementing keywords in the BuiltIn library. Changes to keywords are rare and they are always done so that old usage is first deprecated. One of the most useful methods is replace_variables which allows accessing currently available variables. The following example demonstrates how to get ${OUTPUT_DIR} which is one of the many handy automatic variables. It is also possible to set new variables from libraries using set_test_variable, set_suite_variable and set_global_variable.
使用最安全的API是在内置库中实现关键字的方法。对关键字的更改很少,并且总是这样做,以便首先弃用旧用法。最有用的方法之一是replace_variables,它允许访问当前可用的变量。下面的例子演示了如何获取${OUTPUT_NULL},它是许多方便的自动变量之一。也可以使用set_test_variableset_suite_variableset_global_variable从库中设置新变量。

import os.path
from robot.libraries.BuiltIn import BuiltIn


def do_something(argument):
    builtin = BuiltIn()
    output = do_something_that_creates_a_lot_of_output(argument)
    if builtin.robot_running:
        output_dir = builtin.replace_variables('${OUTPUT_DIR}')
    else:
        output_dir = '.'
    with open(os.path.join(output_dir, 'output.txt'), 'w') as file:
        file.write(output)
    print('*HTML* Output written to <a href="output.txt">output.txt</a>')

As the above examples illustrates, BuiltIn also has a convenient robot_running property for detecting is Robot Framework running.
如上面的示例所示,BuiltIn还有一个方便的robot_running属性,用于检测Robot Framework是否正在运行

The only catch with using methods from BuiltIn is that all run_keyword method variants must be handled specially. Methods that use run_keyword methods have to be registered as run keywords themselves using register_run_keyword method in BuiltIn module. This method's documentation explains why this needs to be done and obviously also how to do it.
使用BuiltIn方法的唯一问题是所有run_keyword方法变体都必须经过特殊处理。使用run_keyword方法的方法必须在BuiltIn模块中使用register_run_keyword方法注册为run关键字。这个方法的文档解释了为什么需要这样做,当然也解释了如何做。

4.1.9   Extending existing test libraries
4.1.9扩展现有测试库

This section explains different approaches how to add new functionality to existing test libraries and how to use them in your own libraries otherwise.
本节解释了如何向现有测试库添加新功能以及如何在您自己的库中使用它们的不同方法。

Modifying original source code
修改原始源代码

If you have access to the source code of the library you want to extend, you can naturally modify the source code directly. The biggest problem of this approach is that it can be hard for you to update the original library without affecting your changes. For users it may also be confusing to use a library that has different functionality than the original one. Repackaging the library may also be a big extra task.
如果您可以访问想要扩展的库的源代码,那么您自然可以直接修改源代码。这种方法的最大问题是,您很难在不影响更改的情况下更新原始库。对于用户来说,使用与原始库功能不同的库也可能会令人困惑。重新打包库也可能是一项很大的额外任务。

This approach works extremely well if the enhancements are generic and you plan to submit them back to the original developers. If your changes are applied to the original library, they are included in the future releases and all the problems discussed above are mitigated. If changes are non-generic, or you for some other reason cannot submit them back, the approaches explained in the subsequent sections probably work better.
如果增强功能是通用的,并且您计划将它们提交回原始开发人员,则这种方法非常有效。如果您的更改应用于原始库,则它们将包含在未来的版本中,并且上面讨论的所有问题都将得到缓解。如果更改是非通用的,或者您由于其他原因无法将它们提交回来,那么后续部分中解释的方法可能会工作得更好。

Using inheritance 使用继承

Another straightforward way to extend an existing library is using inheritance. This is illustrated by the example below that adds new Title Should Start With keyword to the SeleniumLibrary.
扩展现有库的另一种直接方法是使用继承。下面的示例说明了这一点,该示例将新的Title Should Start With关键字添加到SeleniumLibrary

from SeleniumLibrary import SeleniumLibrary
from SeleniumLibrary.base import keyword


class ExtendedSeleniumLibrary(SeleniumLibrary):

    @keyword
    def title_should_start_with(self, expected):
        title = self.get_title()
        if not title.startswith(expected):
            raise AssertionError("Title '%s' did not start with '%s'"
                                 % (title, expected))

A big difference with this approach compared to modifying the original library is that the new library has a different name than the original. A benefit is that you can easily tell that you are using a custom library, but a big problem is that you cannot easily use the new library with the original. First of all your new library will have same keywords as the original meaning that there is always conflict. Another problem is that the libraries do not share their state.
与修改原始库相比,这种方法的一个很大区别是新库的名称与原始库不同。一个好处是,您可以很容易地知道您正在使用一个自定义库,但一个大问题是,您不能轻松地将新库与原始库一起使用。首先,你的新库将有相同的关键字作为原来的含义,总是有冲突。另一个问题是库不共享它们的状态。

This approach works well when you start to use a new library and want to add custom enhancements to it from the beginning. Otherwise other mechanisms explained in this section are probably better.
当您开始使用一个新的库,并希望从一开始就向它添加自定义增强功能时,这种方法非常有效。否则,本节中解释的其他机制可能更好。

Using other libraries directly
直接使用其他库

Because test libraries are technically just classes or modules, a simple way to use another library is importing it and using its methods. This approach works great when the methods are static and do not depend on the library state. This is illustrated by the earlier example that uses Robot Framework's BuiltIn library.
因为测试库在技术上只是类或模块,所以使用另一个库的简单方法是导入它并使用它的方法。当方法是静态的并且不依赖于库状态时,这种方法非常有效。这在前面使用Robot Framework的BuiltIn库的示例中得到了说明。

If the library has state, however, things may not work as you would hope. The library instance you use in your library will not be the same as the framework uses, and thus changes done by executed keywords are not visible to your library. The next section explains how to get an access to the same library instance that the framework uses.
然而,如果库具有状态,那么事情可能不会像您希望的那样工作。您在库中使用的库实例将与框架使用的库实例不同,因此执行的关键字所做的更改对您的库不可见。下一节将解释如何访问框架使用的同一个库实例。

Getting active library instance from Robot Framework
从Robot Framework获取活动库实例

BuiltIn keyword Get Library Instance can be used to get the currently active library instance from the framework itself. The library instance returned by this keyword is the same as the framework itself uses, and thus there is no problem seeing the correct library state. Although this functionality is available as a keyword, it is typically used in test libraries directly by importing the BuiltIn library class as discussed earlier. The following example illustrates how to implement the same Title Should Start With keyword as in the earlier example about using inheritance.
内置关键字Get Library Instance可用于从框架本身获取当前活动的库实例。此关键字返回的库实例与框架本身使用的库实例相同,因此查看正确的库状态没有问题。虽然此功能可以作为关键字使用,但通常通过导入BuiltIn库类直接在测试库中使用,如前所述。下面的示例阐释如何实现与前面有关使用继承的示例中相同的Title Should Start With关键字。

from robot.libraries.BuiltIn import BuiltIn


def title_should_start_with(expected):
    seleniumlib = BuiltIn().get_library_instance('SeleniumLibrary')
    title = seleniumlib.get_title()
    if not title.startswith(expected):
        raise AssertionError("Title '%s' did not start with '%s'"
                             % (title, expected))

This approach is clearly better than importing the library directly and using it when the library has a state. The biggest benefit over inheritance is that you can use the original library normally and use the new library in addition to it when needed. That is demonstrated in the example below where the code from the previous examples is expected to be available in a new library SeLibExtensions.
这种方法显然比直接导入库并在库有状态时使用它要好。与继承相比,最大的好处是您可以正常使用原始库,并在需要时使用新库。下面的示例演示了这一点,其中前面示例中的代码预计将在新的库SeLibExtensions中可用。

*** Settings ***
Library    SeleniumLibrary
Library    SeLibExtensions

*** Test Cases ***
Example
    Open Browser    http://example      # SeleniumLibrary
    Title Should Start With    Example  # SeLibExtensions

Libraries using dynamic or hybrid API
使用动态或混合API的库

Test libraries that use the dynamic or hybrid library API often have their own systems how to extend them. With these libraries you need to ask guidance from the library developers or consult the library documentation or source code.
使用动态混合库API的测试库通常有自己的系统来扩展它们。对于这些库,您需要向库开发人员寻求指导,或者查阅库文档或源代码。

4.2   Remote library interface
4.2远程库接口

The remote library interface provides means for having test libraries on different machines than where Robot Framework itself is running, and also for implementing libraries using other languages than the natively supported Python. For a test library, user remote libraries look pretty much the same as any other test library, and developing test libraries using the remote library interface is also very close to creating normal test libraries.
远程库接口提供了在不同机器上测试库的方法,而不是在机器人框架本身运行的机器上,也可以使用本机支持的Python之外的其他语言实现库。对于一个测试库,用户远程库看起来和其他测试库几乎一样,使用远程库接口开发测试库也非常接近于创建普通的测试库

4.2.1   Introduction 4.2.1引言

There are two main reasons for using the remote library API:
使用远程库API的主要原因有两个:

  • It is possible to have actual libraries on different machines than where Robot Framework is running. This allows interesting possibilities for distributed testing.
    实际的库可能位于不同的机器上,而不是运行Robot Framework的机器上。这为分布式测试提供了有趣的可能性。
  • Test libraries can be implemented using any language that supports XML-RPC protocol. There exists ready-made generic remote servers for various languages like Python, Java, Ruby, .NET, and so on.
    测试库可以使用任何支持XML-RPC协议的语言来实现。存在现成的通用远程服务器,用于各种语言,如Python,Java,Ruby,.NET等。

The remote library interface is provided by the Remote library that is one of the standard libraries. This library does not have any keywords of its own, but it works as a proxy between the core framework and keywords implemented elsewhere. The Remote library interacts with actual library implementations through remote servers, and the Remote library and servers communicate using a simple remote protocol on top of an XML-RPC channel. The high level architecture of all this is illustrated in the picture below:
远程库接口由标准库之一的远程库提供。这个库本身没有任何关键字,但它可以作为核心框架和其他地方实现的关键字之间的代理。远程库通过远程服务器与实际的库实现进行交互,并且远程库和服务器使用XML-RPC通道之上的简单远程协议进行通信。所有这些的高级架构如下图所示:

src/ExtendingRobotFramework/remote.png

Robot Framework architecture with Remote library
带有远程库的机器人框架架构

Note 注意

The remote client uses Python's standard XML-RPC module. It does not support custom XML-RPC extensions implemented by some XML-RPC servers.
远程客户端使用Python的标准XML-RPC模块。它不支持某些XML-RPC服务器实现的自定义XML-RPC扩展。

4.2.2   Putting Remote library to use
4.2.2使用远程库

Importing Remote library 远程图书馆

The Remote library needs to know the address of the remote server but otherwise importing it and using keywords that it provides is no different to how other libraries are used. If you need to use the Remote library multiple times in a suite, or just want to give it a more descriptive name, you can give it an alias when importing it.
远程库需要知道远程服务器的地址,但是导入它并使用它提供的关键字与使用其他库没有什么不同。如果您需要在套件中多次使用远程库,或者只是想为其提供一个更具描述性的名称,则可以在导入时为其提供别名

*** Settings ***
Library    Remote    http://127.0.0.1:8270       AS    Example1
Library    Remote    http://example.com:8080/    AS    Example2
Library    Remote    http://10.0.0.2/example    1 minute    AS    Example3

The URL used by the first example above is also the default address that the Remote library uses if no address is given.
上面第一个示例使用的URL也是Remote库在没有给出地址时使用的默认地址。

The last example above shows how to give a custom timeout to the Remote library as an optional second argument. The timeout is used when initially connecting to the server and if a connection accidentally closes. Timeout can be given in Robot Framework time format like 60s or 2 minutes 10 seconds. The default timeout is typically several minutes, but it depends on the operating system and its configuration. Notice that setting a timeout that is shorter than keyword execution time will interrupt the keyword.
上面的最后一个示例展示了如何将自定义超时作为可选的第二个参数提供给Remote库。超时在最初连接到服务器时以及连接意外关闭时使用。时间可以以Robot Framework的时间格式给出,如60秒2分10秒。默认超时通常为几分钟,但取决于操作系统及其配置。请注意,设置一个短于关键字执行时间的超时将中断关键字。

Note 注意

Port 8270 is the default port that remote servers are expected to use and it has been registered by IANA for this purpose. This port number was selected because 82 and 70 are the ASCII codes of letters R and F, respectively.
端口8270是远程服务器预计使用的默认端口,并且已由IANA为此目的注册。选择此端口号是因为82和70分别是字母RF的ASCII码。

Note 注意

When connecting to the local machine, it is recommended to use IP address 127.0.0.1 instead of machine name localhost. This avoids address resolution that can be extremely slow at least on Windows.
连接到本地计算机时,建议使用IP地址127.0.0.1而不是计算机名称localhost。这避免了至少在Windows上可能非常慢的地址解析。

Note 注意

If the URI contains no path after the server address, the XML-RPC module used by the Remote library will use /RPC2 path by default. In practice using http://127.0.0.1:8270 is thus identical to using http://127.0.0.1:8270/RPC2. Depending on the remote server this may or may not be a problem. No extra path is appended if the address has a path even if the path is just /. For example, neither http://127.0.0.1:8270/ nor http://127.0.0.1:8270/my/path will be modified.
如果URI在服务器地址后不包含路径,则远程库使用的XML-RPC模块将默认使用/RPC 2路径。因此,实际上使用http://127.0.0.1:8270与使用http://127.0.0.1:8270/RPC2是相同的。根据远程服务器的不同,这可能是一个问题,也可能不是。如果地址有路径,即使路径只是/,也不会附加额外的路径。例如,http://127.0.0.1:8270/http://127.0.0.1:8270/my/path都不会被修改。

Starting and stopping remote servers
启动和停止远程服务器

Before the Remote library can be imported, the remote server providing the actual keywords must be started. If the server is started before launching the test execution, it is possible to use the normal Library setting like in the above example. Alternatively other keywords, for example from Process or SSH libraries, can start the server up, but then you may need to use Import Library keyword because the library is not available when the test execution starts.
在导入远程库之前,必须启动提供实际关键字的远程服务器。如果在启动测试执行之前启动服务器,则可以像上面的示例中那样使用正常的库设置。或者,其他关键字,例如ProcessSSH库,可以启动服务器,但随后您可能需要使用Import Library关键字,因为测试执行开始时库不可用。

How a remote server can be stopped depends on how it is implemented. Typically servers support the following methods:
如何停止远程服务器取决于它是如何实现的。通常,服务器支持以下方法:

  • Regardless of the library used, remote servers should provide Stop Remote Server keyword that can be easily used by executed tests.
    无论使用什么库,远程服务器都应该提供Stop Remote Server关键字,以便执行的测试可以轻松使用。
  • Remote servers should have stop_remote_server method in their XML-RPC interface.
    远程服务器应该在其XML-RPC接口中具有stop_remote_server方法。
  • Hitting Ctrl-C on the console where the server is running should stop the server.
    在运行服务器的控制台上按Ctrl-C应该会停止服务器。
  • The server process can be terminated using tools provided by the operating system (e.g. kill).
    可以使用操作系统提供的工具(例如 kill )终止服务器进程。

Note 注意

Servers may be configured so that users cannot stop it with Stop Remote Server keyword or stop_remote_server method.
服务器可以配置为使用户无法使用Stop Remote Server关键字或stop_remote_server方法停止它。

4.2.3   Supported argument and return value types
4.2.3支持的参数和返回值类型

Because the XML-RPC protocol does not support all possible object types, the values transferred between the Remote library and remote servers must be converted to compatible types. This applies to the keyword arguments the Remote library passes to remote servers and to the return values servers give back to the Remote library.
由于XML-RPC协议不支持所有可能的对象类型,因此在远程库和远程服务器之间传输的值必须转换为兼容的类型。这适用于远程库传递给远程服务器的关键字参数以及服务器返回给远程库的返回值。

Both the Remote library and the Python remote server handle Python values according to the following rules. Other remote servers should behave similarly.
远程库和Python远程服务器都根据以下规则处理Python值。其他远程服务器的行为应该类似。

  • Strings, numbers and Boolean values are passed without modifications.
    字符串、数字和布尔值不加修改地传递。
  • Python None is converted to an empty string.
    PythonNone被转换为空字符串。
  • All lists, tuples, and other iterable objects (except strings and dictionaries) are passed as lists so that their contents are converted recursively.
    所有列表、元组和其他可迭代对象(字符串和字典除外)都作为列表传递,以便递归转换其内容。
  • Dictionaries and other mappings are passed as dicts so that their keys are converted to strings and values converted to supported types recursively.
    字典和其他映射作为dict传递,以便它们的键被转换为字符串,值被递归地转换为支持的类型。
  • Returned dictionaries are converted to so called dot-accessible dicts that allow accessing keys as attributes using the extended variable syntax like ${result.key}. This works also with nested dictionaries like ${root.child.leaf}.
    返回的字典被转换为所谓的点可访问的字典,允许使用扩展的变量语法(如${result.key})访问键作为属性。这也适用于像${root.child.leaf}这样的嵌套字典。
  • Strings containing bytes in the ASCII range that cannot be represented in XML (e.g. the null byte) are sent as Binary objects that internally use XML-RPC base64 data type. Received Binary objects are automatically converted to byte strings.
    包含ASCII范围内的字节的字符串不能用XML表示(例如空字节),作为内部使用XML-RPC base64数据类型的Binary对象发送。接收到的二进制对象会自动转换为字节字符串。
  • Other types are converted to strings.
    其他类型转换为字符串。

4.2.4   Remote protocol 4.2.4远程协议

This section explains the protocol that is used between the Remote library and remote servers. This information is mainly targeted for people who want to create new remote servers.
本节介绍远程库和远程服务器之间使用的协议。此信息主要针对想要创建新远程服务器的人。

The remote protocol is implemented on top of XML-RPC, which is a simple remote procedure call protocol using XML over HTTP. Most mainstream languages (Python, Java, C, Ruby, Perl, Javascript, PHP, ...) have a support for XML-RPC either built-in or as an extension.
远程协议是在XML-RPC之上实现的,XML-RPC是一种使用XML over HTTP的简单远程过程调用协议。大多数主流语言(Python、Java、C、Ruby、Perl、JavaScript、PHP等)支持XML-RPC,无论是内置的还是作为扩展。

The Python remote server can be used as a reference implementation.
Python远程服务器可以用作参考实现。

Required methods 需方法

There are two possibilities how remote servers can provide information about the keywords they contain. They are briefly explained below and documented more thoroughly in the subsequent sections.
有两种可能性远程服务器可以提供有关它们所包含的关键字的信息。下文将简要说明这些问题,并在随后的章节中更详细地记录这些问题。

  1. Remote servers can implement the same methods as the dynamic library API has. This means get_keyword_names method and optional get_keyword_arguments, get_keyword_types, get_keyword_tags and get_keyword_documentation methods. Notice that using "camel-case names" like getKeywordNames is not possible similarly as in the normal dynamic API.
    远程服务器可以实现与动态库API相同的方法。这意味着get_keyword_names方法和可选的get_keyword_argumentsget_keyword_typesget_keyword_tagsget_keyword_documentation方法。请注意,使用类似getKeywordNames的“大小写名称”与在普通动态API中使用类似是不可能的。
  2. Starting from Robot Framework 4.0, remote servers can have a single get_library_information method that returns all library and keyword information as a single dictionary. If a remote server has this method, the other getter methods like get_keyword_names are not used at all. This approach has the benefit that there is only one XML-RPC call to get information while the approach explained above requires several calls per keyword. With bigger libraries the difference can be significant.
    从Robot Framework 4.0开始,远程服务器可以有一个get_library_information方法,该方法将所有库和关键字信息作为一个字典返回。如果一个远程服务器有这个方法,那么其他的getter方法,比如get_keyword_names,就根本不用了。这种方法的好处是,只有一个XML-RPC调用来获取信息,而上面解释的方法需要每个关键字几个调用。对于更大的库,差异可能很大。

Regardless how remote servers provide information about their keywords, they must have run_keyword method that is used when keywords are executed. How the actual keywords are implemented is not relevant for the Remote library. Remote servers can either act as wrappers for the real test libraries, like the available generic remote servers do, or they can implement keywords themselves.
无论远程服务器如何提供有关其关键字的信息,它们都必须具有在执行关键字时使用的run_keyword方法。如何实现实际的关键字与Remote库无关。远程服务器既可以充当真实的测试库的包装器,就像可用的通用远程服务器一样,也可以自己实现关键字。

Remote servers should additionally have stop_remote_server method in their public interface to ease stopping them. They should also automatically expose this method as Stop Remote Server keyword to allow using it in the test data regardless of the test library. Allowing users to stop the server is not always desirable, and servers may support disabling this functionality somehow. The method, and also the exposed keyword, should return True or False depending on whether stopping is allowed or not. That makes it possible for external tools to know if stopping the server succeeded.
远程服务器应该在其公共接口中添加stop_remote_server方法,以方便停止它们。它们还应该自动将此方法公开为Stop Remote Server关键字,以允许在测试数据中使用它,而不管测试库是什么。允许用户停止服务器并不总是可取的,服务器可能会以某种方式支持禁用此功能。该方法以及暴露的关键字应该返回TrueFalse,这取决于是否允许停止。这使得外部工具可以知道停止服务器是否成功。

Using get_keyword_names and keyword specific getters
使用get_keyword_names和特定于关键字的getter

This section explains how the Remote library gets keyword names and other information when the server implements get_keyword_names. The next sections covers using the newer get_library_info method.
本节解释当服务器实现get_keyword_names时,Remote库如何获取关键字名称和其他信息。下一节将介绍如何使用较新的get_library_info方法。

The get_keyword_names method must return names of the keyword the server contains as a list of strings. Remote servers can, and should, also implement get_keyword_arguments, get_keyword_types, get_keyword_tags and get_keyword_documentation methods to provide more information about the keywords. All these methods take the name of the keyword as an argument and what they must return is explained in the table below.
get_keyword_names方法必须以字符串列表的形式返回服务器包含的关键字的名称。远程服务器可以也应该实现get_keyword_argumentsget_keyword_typesget_keyword_tagsget_keyword_documentation方法,以提供有关关键字的更多信息。所有这些方法都以关键字的名称作为参数,它们必须返回的内容在下表中解释。

Keyword specific getter methods
关键字特定的getter方法
Method 方法 Return value 返回值
get_keyword_arguments Arguments as a list of strings in the same format as with dynamic libraries.
参数作为字符串列表,格式与动态库相同
get_keyword_types Type information as a list or dictionary of strings. See below for details.
以字符串列表或字典的形式键入信息。详情请参见下文。
get_keyword_documentation Documentation as a string.
文档作为字符串。
get_keyword_tags Tags as a list of strings.
标记作为字符串列表。

Type information used for argument conversion can be returned either as a list mapping type names to arguments based on position or as a dictionary mapping argument names to type names directly. In practice this works the same way as when specifying types using the @keyword decorator with normal libraries. The difference is that because the XML-RPC protocol does not support arbitrary values, type information needs to be specified using type names or aliases like 'int' or 'integer', not using actual types like int. Additionally None or null values may not be allowed by the XML-RPC server, but an empty string can be used to indicate that certain argument does not have type information instead.
用于参数转换的类型信息可以作为基于位置将类型名映射到参数的列表返回,也可以作为直接将参数名映射到类型名的字典返回。实际上,这与使用@关键字装饰器指定普通库的类型的方式相同。不同之处在于,由于XML-RPC协议不支持任意值,因此需要使用类型名称或别名(如“int”“integer”)指定类型信息,而不是使用实际类型(如int)。此外,XML-RPC服务器可能不允许使用Nonenull值,但可以使用空字符串来指示某些参数没有类型信息。

Argument conversion is supported also based on default values using the same logic as with normal libraries. For this to work, arguments with default values must be returned as tuples, not as strings, the same way as with dynamic libraries. For example, argument conversion works if argument information is returned like [('count', 1), ('caseless', True)] but not if it is ['count=1', 'caseless=True'].
参数转换也支持基于默认值,使用与普通库相同的逻辑。要做到这一点,具有默认值的参数必须作为元组返回,而不是作为字符串返回,这与动态库的方式相同。例如,如果参数信息返回类似[('count',1),('caseless',True)]的形式,则参数转换有效,但如果参数信息返回类似于['count = 1','caseless= True ']的形式,则无效。

Remote servers can also provide general library documentation to be used when generating documentation with the Libdoc tool. This information is got by calling get_keyword_documentation with special values __intro__ and __init__.
远程服务器还可以提供在使用Libdoc工具生成文档时使用的通用库文档。这个信息是通过调用get_keyword_documentation来获得的,它带有特殊的值__intro____init__

Note 注意

get_keyword_types is new in Robot Framework 3.1 and support for argument conversion based on defaults is new in Robot Framework 4.0.
get_keyword_types是Robot Framework 3.1中的新增功能,而基于默认值的参数转换支持是Robot Framework 4.0中的新增功能。

Using get_library_information
使用get_library_information

The get_library_information method allows returning information about the whole library in one XML-RPC call. The information must be returned as a dictionary where keys are keyword names and values are nested dictionaries containing keyword information. The dictionary can also contain separate entries for generic library information.
get_library_information方法允许在一次XML-RPC调用中返回有关整个库的信息。信息必须作为字典返回,其中键是关键字名称,值是包含关键字信息的嵌套字典。字典还可以包含用于通用库信息的单独条目。

The keyword information dictionary can contain keyword arguments, documentation, tags and types, and the respective keys are args, doc, tags and types. Information must be provided using same semantics as when get_keyword_arguments, get_keyword_documentation, get_keyword_tags and get_keyword_types discussed in the previous section. If some information is not available, it can be omitted from the info dictionary altogether.
关键字信息字典可以包含关键字参数、文档、标签和类型,并且相应的键是argsdoc标签类型。必须使用与上一节中讨论的get_keyword_argumentsget_keyword_documentationget_keyword_tagsget_keyword_types相同的语义来提供信息。如果某些信息不可用,则可以将其从info字典中完全省略。

get_library_information supports also returning general library documentation to be used with Libdoc. It is done by including special __intro__ and __init__ entries into the returned library information dictionary.
get_library_information还支持返回与Libdoc一起使用的一般库文档。这是通过在返回的库信息字典中包含特殊的__intro____init__条目来完成的。

For example, a Python library like
例如,像这样的Python库

"""Library documentation."""

from robot.api.deco import keyword

@keyword(tags=['x', 'y'])
def example(a: int, b=True):
    """Keyword documentation."""
    pass

def another():
    pass

could be mapped into this kind of library information dictionary:
可以被映射到这样的图书馆信息词典中:

{
    '__intro__': {'doc': 'Library documentation'}
    'example': {'args': ['a', 'b=True'],
                'types': ['int'],
                'doc': 'Keyword documentation.',
                'tags': ['x', 'y']}
    'another: {'args': []}
}

Note 注意

get_library_information is new in Robot Framework 4.0.
get_library_information是Robot Framework 4.0中的新功能。

Executing remote keywords
执行远程关键字

When the Remote library wants the server to execute some keyword, it calls the remote server's run_keyword method and passes it the keyword name, a list of arguments, and possibly a dictionary of free named arguments. Base types can be used as arguments directly, but more complex types are converted to supported types.
当Remote库希望服务器执行某个关键字时,它会调用远程服务器的run_keyword方法,并向其传递关键字名称、参数列表以及可能的自由命名参数字典。基类型可以直接用作参数,但更复杂的类型会转换为受支持的类型

The server must return results of the execution in a result dictionary (or map, depending on terminology) containing items explained in the following table. Notice that only the status entry is mandatory, others can be omitted if they are not applicable.
服务器必须在结果字典(或映射,取决于术语)中返回执行结果,其中包含下表中解释的项。请注意,只有状态条目是强制性的,如果其他条目不适用,则可以省略。

Entries in the remote result dictionary
在远程结果字典中查找
Name 名称 Explanation 解释
status 地位 Mandatory execution status. Either PASS or FAIL.
强制执行状态。通过或未通过。
output 输出 Possible output to write into the log file. Must be given as a single string but can contain multiple messages and different log levels in format *INFO* First message\n*HTML* <b>2nd</b>\n*WARN* Another message. It is also possible to embed timestamps to the log messages like *INFO:1308435758660* Message with timestamp.
可能要写入日志文件的输出。必须作为单个字符串提供,但可以包含多个消息和不同的日志级别,格式为 *INFO* 第一个消息\n*HTML* <b>2nd</b>\n*WARN* 另一个消息。也可以将时间戳嵌入到日志消息中,如*INFO:1308435758660* 带有时间戳的消息
return 返回 Possible return value. Must be one of the supported types.
可能的返回值。必须是支持的类型之一。
error 误差 Possible error message. Used only when the execution fails.
可能的错误消息。仅在执行失败时使用。
traceback 回溯 Possible stack trace to write into the log file using DEBUG level when the execution fails.
当执行失败时,使用调试级别写入日志文件的可能堆栈跟踪。
continuable 可持续 When set to True, or any value considered True in Python, the occurred failure is considered continuable.
当设置为True或Python中认为是True的任何值时,发生的失败被认为是可持续的。
fatal 致命 Like continuable, but denotes that the occurred failure is fatal.
类似于continuable,但表示发生的故障是致命的。

Different argument syntaxes
不同的参数语法

The Remote library is a dynamic library, and in general it handles different argument syntaxes according to the same rules as any other dynamic library. This includes mandatory arguments, default values, varargs, as well as named argument syntax.
远程库是一个动态库,通常它根据与任何其他动态库相同的规则处理不同的参数语法。这包括强制参数、默认值、变量参数以及命名参数语法

Also free named arguments (**kwargs) works mostly the same way as with other dynamic libraries. First of all, the get_keyword_arguments must return an argument specification that contains **kwargs exactly like with any other dynamic library. The main difference is that remote servers' run_keyword method must have an optional third argument that gets the kwargs specified by the user. The third argument must be optional because, for backwards-compatibility reasons, the Remote library passes kwargs to the run_keyword method only when they have been used in the test data.
自由命名参数(**kwargs)的工作方式与其他动态库基本相同。首先,get_keyword_arguments必须返回一个包含**kwargs的参数规范,就像任何其他动态库一样。主要区别在于远程服务器的run_keyword方法必须有一个可选的第三个参数,用于获取用户指定的kwargs。第三个参数必须是可选的,因为出于向后兼容性的原因,Remote库仅在kwargs已在测试数据中使用时才将其传递给run_keyword方法。

In practice run_keyword should look something like the following Python and Java examples, depending on how the language handles optional arguments.
在实践中,run_keyword应该看起来像下面的Python和Java示例,这取决于语言如何处理可选参数。

def run_keyword(name, args, kwargs=None):
    # ...
public Map run_keyword(String name, List args) {
    // ...
}

public Map run_keyword(String name, List args, Map kwargs) {
    // ...
}

4.3   Listener interface 4.3侦听器接口

Robot Framework's listener interface provides a powerful mechanism for getting notifications and for inspecting and modifying data and results during execution. Listeners are called, for example, when suites, tests and keywords start and end, when output files are ready, and finally when the whole execution ends. Example usages include communicating with external test management systems, sending a message when a test fails, and modifying tests during execution.
Robot Framework的侦听器接口提供了一个强大的机制,用于获取通知以及在执行期间检查和修改数据和结果。例如,当套件、测试和关键字开始和结束时,当输出文件准备就绪时,以及最后当整个执行结束时,都会调用侦听器。示例用法包括与外部测试管理系统通信,在测试失败时发送消息,以及在执行期间修改测试。

Listeners are implemented as classes or modules with certain special methods. They can be taken into use from the command line and be registered by libraries. The former listeners are active during the whole execution while the latter are active only when executing suites where libraries registering them are imported.
侦听器是用类或模块实现的,并带有某些特殊的方法。它们可以从命令行使用并由库注册。前一个监听器在整个执行过程中都是活动的,而后者只在执行套件时才是活动的,其中注册它们的库被导入。

There are two supported listener interface versions, listener version 2 and listener version 3. They have mostly the same methods, but these methods are called with different arguments. The newer listener version 3 is more powerful and generally recommended.
有两个受支持的侦听器接口版本,侦听器版本2侦听器版本3。它们有基本相同的方法,但是这些方法被不同的参数调用。较新的侦听器版本3功能更强大,通常推荐使用。

4.3.1   Listener structure 4.3.1管道结构

Listeners are implement as modules or classes similarly as libraries. They can implement certain named hook methods depending on what events they are interested in. For example, if a listener wants to get a notification when a test starts, it can implement the start_test method. As discussed in the subsequent sections, different listener versions have slightly different set of available methods and they also are called with different arguments.
监听器被实现为类似于库的模块或类。它们可以根据自己感兴趣的事件实现特定的命名钩子方法。例如,如果侦听器希望在测试开始时获得通知,则可以实现start_test方法。正如后面的部分所讨论的,不同的侦听器版本有稍微不同的可用方法集,并且它们也是用不同的参数调用的。

# Listener implemented as a module using the listener API version 3.

def start_suite(data, result):
    print(f"Suite '{data.name}' starting.")

def end_test(data, result):
    print(f"Test '{result.name}' ended with status {result.status}.")

Listeners do not need to implement any explicit interface, it is enough to simply implement needed methods and they will be recognized automatically. There are, however, base classes robot.api.interfaces.ListenerV2 and robot.api.interfaces.ListenerV3 that can be used to get method name completion in editors, type hints, and so on.
侦听器不需要实现任何显式的接口,只需实现所需的方法就足够了,它们将被自动识别。但是,有一些基类robot.api.interfaces.ListenerV2robot.api.interfaces.ListenerV3可用于在编辑器中获得方法名称完成、类型提示等。

# Same as the above example, but uses an optional base class and type hints.

from robot import result, running
from robot.api.interfaces import ListenerV3


class Example(ListenerV3):

    def start_suite(self, data: running.TestSuite, result: result.TestSuite):
        print(f"Suite '{data.name}' starting.")

    def end_test(self, data: running.TestCase, result: result.TestCase):
        print(f"Test '{result.name}' ended with status {result.status}.")

Note 注意

Optional listener base classes are new in Robot Framework 6.1.
可选的侦听器基类是Robot Framework 6.1中新增的。

In addition to using "snake case" like start_test with listener method names, it is possible to use "camel case" like startTest. This support was added when it was possible to run Robot Framework on Jython and implement listeners using Java. It is preserved for backwards compatibility reasons, but not recommended with new listeners.
除了使用“snake case”(如start_test)和侦听器方法名称之外,还可以使用“camel case”(如startTest)。当可以在Jython上运行Robot Framework并使用Java实现侦听器时,添加了此支持。出于向后兼容性的原因,它被保留,但不建议用于新的侦听器。

4.3.2   Listener interface versions
4.3.2以太网接口版本

There are two supported listener interface versions with version numbers 2 and 3. A listener can specify which version to use by having a ROBOT_LISTENER_API_VERSION attribute with value 2 or 3, respectively. Starting from Robot Framework 7.0, the listener version 3 is used by default if the version is not specified.
有两个受支持的侦听器接口版本,版本号为2和3。侦听器可以通过将ROBOT_LISTENER_API_VERSION属性的值分别设置为2或3来指定要使用的版本。从Robot Framework 7.0开始,如果未指定版本,则默认使用侦听器版本3。

Listener version 2 and listener version 3 have mostly the same methods, but arguments passed to these methods are different. Arguments given to listener 2 methods are strings and dictionaries containing information about execution. This information can be inspected and sent further, but it is not possible to modify it directly. Listener 3 methods get the same model objects that Robot Framework itself uses, and these model objects can be both inspected and modified.
监听器版本2监听器版本3具有基本相同的方法,但传递给这些方法的参数不同。提供给listener 2方法的参数是包含有关执行信息的字符串和字典。这些信息可以进一步检查和发送,但不能直接修改。Robot Framework 3方法获取与Robot Framework本身使用的相同的模型对象,并且这些模型对象可以被检查和修改。

Listener version 3 is more powerful than the older listener version 2 and generally recommended.
监听器版本3比旧的监听器版本2功能更强大,通常推荐使用。

Listener version 2 第二版

Listeners using the listener API version 2 get notifications about various events during execution, but they do not have access to actually executed tests and thus cannot directly affect the execution or created results.
使用侦听器API版本2的侦听器在执行期间获得有关各种事件的通知,但它们不能访问实际执行的测试,因此不能直接影响执行或创建的结果。

Listener methods in the API version 2 are listed in the following table and in the API docs of the optional ListenerV2 base class. All methods related to test execution progress have the same signature method(name, attributes), where attributes is a dictionary containing details of the event. Listener methods are free to do whatever they want to do with the information they receive, but they cannot directly change it. If that is needed, listener version 3 can be used instead.
下表和可选ListenerV2基类的API文档中列出了API版本2中的方法。所有与测试执行进度相关的方法都具有相同的签名方法(名称,属性),其中属性是包含事件详细信息的字典。监听器方法可以自由地对接收到的信息做任何事情,但不能直接改变它。如果需要的话,可以使用监听器版本3

Methods in the listener API 2
监听器API中的方法2
Method 方法 Arguments 论点 Documentation 文件
start_suite 起始套件 name, attributes 名称,属性

Called when a test suite starts.
在测试套件启动时调用。

Contents of the attribute dictionary:
属性字典的内容:

  • id: Suite id. s1 for the top level suite, s1-s1 for its first child suite, s1-s2 for the second child, and so on.
    id:套房id。s1代表顶层套房,s1-s1代表第一个孩子套房,s1-s2代表第二个孩子,以此类推。
  • longname: Suite name including parent suites.
    longname:套件名称,包括父套件。
  • doc: Suite documentation.
    doc:套件文档。
  • metadata: Free suite metadata as a dictionary.
    metadata免费的套件元数据字典。
  • source: An absolute path of the file/directory the suite was created from.
    source:创建套件的文件/目录的绝对路径。
  • suites: Names of the direct child suites this suite has as a list.
    套房:该套房的直接儿童套房的名称列表。
  • tests: Names of the tests this suite has as a list. Does not include tests of the possible child suites.
    tests:此套件以列表形式列出的测试名称。不包括可能的儿童套房的测试。
  • totaltests: The total number of tests in this suite. and all its sub-suites as an integer.
    totaltests:此套件中的测试总数。和它的所有子套件作为一个整数。
  • starttime: Suite execution start time.
    starttime:套件执行开始时间。
end_suite 尾套 name, attributes 名称,属性

Called when a test suite ends.
在测试套件结束时调用。

Contents of the attribute dictionary:
属性字典的内容:

  • id: Same as in start_suite.
    id:与start_suite中相同。
  • longname: Same as in start_suite.
    longname:与start_suite中相同。
  • doc: Same as in start_suite.
    doc:与start_suite中相同。
  • metadata: Same as in start_suite.
    metadata:与start_suite中相同。
  • source: Same as in start_suite.
    source:与start_suite中相同。
  • starttime: Same as in start_suite.
    starttime:与start_suite中相同。
  • endtime: Suite execution end time.
    endtime:套件执行结束时间。
  • elapsedtime: Total execution time in milliseconds as an integer
    elapsedtime:总执行时间,以毫秒为单位,为整数
  • status: Suite status as string PASS, FAIL or SKIP.
    status:套件状态为字符串PASSFAILSKIP
  • statistics: Suite statistics (number of passed and failed tests in the suite) as a string.
    statistics:套件统计数据(套件中通过和失败的测试数量)作为字符串。
  • message: Error message if suite setup or teardown has failed, empty otherwise.
    消息:如果套件设置或拆除失败,则出现错误消息,否则为空。
start_test 起动试验 name, attributes 名称,属性

Called when a test case starts.
在测试用例开始时调用。

Contents of the attribute dictionary:
属性字典的内容:

  • id: Test id in format like s1-s2-t2, where the beginning is the parent suite id and the last part shows test index in that suite.
    id:测试id,格式如s1-s2-t2,其中开头是父套件id,最后一部分显示该套件中的测试索引。
  • longname: Test name including parent suites.
    longname:包含父套件的测试名称。
  • originalname: Test name with possible variables unresolved. New in RF 3.2.
    originalname:测试名称,可能有未解析的变量。RF 3.2中的新功能。
  • doc: Test documentation.
    doc:测试文档。
  • tags: Test tags as a list of strings.
    tags:将标签作为字符串列表进行测试。
  • template: The name of the template used for the test. An empty string if the test not templated.
    template:用于测试的模板的名称。如果测试未模板化,则为空字符串。
  • source: An absolute path of the test case source file. New in RF 4.0.
    source:测试用例源文件的绝对路径。RF 4.0中的新功能。
  • lineno: Line number where the test starts in the source file. New in RF 3.2.
    lineno:源文件中测试开始的行号。RF 3.2中的新功能。
  • starttime: Test execution execution start time.
    starttime:测试执行开始时间。
end_test 端部试验 name, attributes 名称,属性

Called when a test case ends.
在测试用例结束时调用。

Contents of the attribute dictionary:
属性字典的内容:

  • id: Same as in start_test.
    id:与start_test相同。
  • longname: Same as in start_test.
    longname:与start_test中相同。
  • originalname: Same as in start_test.
    originalname:与start_test中相同。
  • doc: Same as in start_test.
    doc:与start_test中相同。
  • tags: Same as in start_test.
    tags:与start_test相同。
  • template: Same as in start_test.
    template:与start_test中相同。
  • source: Same as in start_test.
    source:与start_test相同。
  • lineno: Same as in start_test.
    lineno:与start_test中相同。
  • starttime: Same as in start_test.
    starttime:与start_test相同。
  • endtime: Test execution execution end time.
    endtime:测试执行结束时间。
  • elapsedtime: Total execution time in milliseconds as an integer
    elapsedtime:总执行时间,以毫秒为单位,为整数
  • status: Test status as string PASS, FAIL or SKIP.
    status:测试状态为字符串PASSFAILSKIP
  • message: Status message. Normally an error message or an empty string.
    message:状态消息。通常是错误消息或空字符串。
start_keyword name, attributes 名称,属性

Called when a keyword or a control structure such as IF/ELSE or TRY/EXCEPT starts.
当关键字或控制结构(如IF/ELSETRY/EXCEPT)启动时调用。

With keywords name is the full keyword name containing possible library or resource name as a prefix like MyLibrary.Example Keyword. With control structures name contains string representation of parameters.
With keywordsname是完整的关键字名称,包含可能的库或资源名称作为前缀,如MyLibrary。用控制结构的名称包含参数的字符串表示。

Keywords and control structures share most of attributes, but control structures can have additional attributes depending on their type.
关键字和控制结构共享大部分属性,但控制结构可以根据其类型拥有其他属性。

Shared attributes: 共享属性:

  • type: String specifying type of the started item. Possible values are: KEYWORD, SETUP, TEARDOWN, FOR, WHILE, ITERATION, IF, ELSE IF, ELSE, TRY, EXCEPT, FINALLY, VAR, RETURN, BREAK, CONTINUE and ERROR. All type values were changed in RF 4.0 and in RF 5.0 FOR ITERATION was changed to ITERATION.
    type:指定启动项类型的字符串。可能的值有:KEYWORDSETUPTEARDOWNFORWHILEITERATIONIFELSE IFELSETRYEXCEPTFINALLYVARRETURNBREAKCONTINUEERROR。在RF 4.0中更改了所有类型值,并在RF 5.0中将“迭代”更改为“迭代
  • kwname: Name of the keyword without library or resource prefix. String representation of parameters with control structures.
    kwname:不带库或资源前缀的关键字的名称。具有控制结构的参数的字符串表示形式。
  • libname: Name of the library or resource file the keyword belongs to. An empty string with user keywords in a test case file and with control structures.
    libname:关键字所属的库或资源文件的名称。测试用例文件中带有用户关键字和控制结构的空字符串。
  • doc: Keyword documentation.
    doc:关键字文档。
  • args: Keyword's arguments as a list of strings.
    args:关键字的参数作为字符串列表。
  • assign: A list of variable names that keyword's return value is assigned to.
    assign:关键字返回值被赋给的变量名列表。
  • tags: Keyword tags as a list of strings.
    tages关键字标签作为字符串列表。
  • source: An absolute path of the file where the keyword was used. New in RF 4.0.
    source:使用关键字的文件的绝对路径。RF 4.0中的新功能。
  • lineno: Line where the keyword was used. New in RF 4.0.
    lineno:使用关键字的行。RF 4.0中的新功能。
  • status: Initial keyword status. NOT RUN if keyword is not executed (e.g. due to an earlier failure), NOT SET otherwise. New in RF 4.0.
    status:初始关键字状态。如果关键字未执行(例如,由于先前的失败),则NOT RUN否则NOT SET。RF 4.0中的新功能。
  • starttime: Keyword execution start time.
    starttime:关键字执行开始时间。

Additional attributes for FOR types:
FOR类型的其他属性:

  • variables: Assigned variables for each loop iteration as a list or strings.
    variables:将每个循环迭代的变量作为列表或字符串。
  • flavor: Type of loop (e.g. IN RANGE).
    flavor:循环的类型(例如IN RANGE)。
  • values: List of values being looped over as a list or strings.
    values:作为列表或字符串循环的值列表。
  • start: Start configuration. Only used with IN ENUMERATE loops. New in RF 6.1.
    start:启动配置。仅用于IN ENUMERATE循环。RF 6.1中的新功能。
  • mode: Mode configuration. Only used with IN ZIP loops. New in RF 6.1.
    mode:模式配置。仅用于IN ZIP循环。RF 6.1中的新功能。
  • fill: Fill value configuration. Only used with IN ZIP loops. New in RF 6.1.
    fill:填充值配置。仅用于IN ZIP循环。RF 6.1中的新功能。

Additional attributes for ITERATION types with FOR loops:
带有FOR循环的ITERATION类型的其他属性:

  • variables: Variables and string representations of their contents for one FOR loop iteration as a dictionary.
    variables:一次FOR循环迭代中的变量及其内容的字符串表示形式,作为字典。

Additional attributes for WHILE types:
WHILE类型的其他属性:

  • condition: The looping condition.
    condition:循环条件。
  • limit: The maximum iteration limit.
    limit:最大迭代限制。
  • on_limit: What to do if the limit is exceeded. Valid values are pass and fail. New in RF 7.0.
    on_limit:如果超出限制,该怎么办。有效值为通过失败。RF 7.0中的新功能。
  • on_limit_message: The custom error raised when the limit of the WHILE loop is reached. New in RF 6.1.
    on_limit_message:当达到WHILE循环的限制时引发的自定义错误。RF 6.1中的新功能。

Additional attributes for IF and ELSE IF types:
IFELSE IF类型的其他属性:

  • condition: The conditional expression being evaluated. With ELSE IF new in RF 6.1.
    condition:正在评估的条件表达式。RF 6.1中新增了ELSE IF

Additional attributes for EXCEPT types:
EXCEPT类型的其他属性:

  • patterns: The exception patterns being matched as a list or strings.
    patterns:以列表或字符串形式匹配的异常模式。
  • pattern_type: The type of pattern match (e.g. GLOB).
    pattern_type:模式匹配的类型(例如GLOB)。
  • variable: The variable containing the captured exception.
    variable:包含捕获的异常的变量。

Additional attributes for RETURN types:
RETURN类型的其他属性:

  • values: Return values from a keyword as a list or strings.
    values:以列表或字符串的形式返回关键字中的值。

Additional attributes for VAR types:
VAR类型的其他属性:

  • name: Variable name.
    name:变量名。
  • value: Variable value. A string with scalar variables and a list otherwise.
    value:变量值。一个带有标量变量的字符串,否则是一个列表。
  • scope: Variable scope (e.g. GLOBAL) as a string.
    scope:变量范围(例如GLOBAL)作为字符串。

Additional attributes for control structures are in general new in RF 6.0. VAR is new in RF 7.0.
控制结构的附加属性通常是RF 6.0中的新特性。VAR是RF 7.0中的新功能。

end_keyword 结束关键字 name, attributes 名称,属性

Called when a keyword or a control structure ends.
当关键字或控制结构结束时调用。

name is the full keyword name containing possible library or resource name as a prefix. For example, MyLibrary.Example Keyword.
name是包含可能的库或资源名称作为前缀的完整关键字名称。例如,MyLibrary.Example关键字

Control structures have additional attributes, which change based on the type attribute. For descriptions of all possible attributes, see the start_keyword section.
控制结构具有附加属性,这些属性根据类型属性而改变。有关所有可能属性的说明,请参见start_keyword部分。

Contents of the attribute dictionary:
属性字典的内容:

  • type: Same as with start_keyword.
    type:与start_keyword相同。
  • kwname: Same as with start_keyword.
    kwname:与start_keyword相同。
  • libname: Same as with start_keyword.
    libname:与start_keyword相同。
  • doc: Same as with start_keyword.
    doc:与start_keyword相同。
  • args: Same as with start_keyword.
    args:与start_keyword相同。
  • assign: Same as with start_keyword.
    assign:与start_keyword相同。
  • tags: Same as with start_keyword.
    tags:与start_keyword相同。
  • source: Same as with start_keyword.
    source:与start_keyword相同。
  • lineno: Same as with start_keyword.
    lineno:与start_keyword相同。
  • starttime: Same as with start_keyword.
    starttime:与start_keyword相同。
  • endtime: Keyword execution end time.
    endtime:关键字执行结束时间。
  • elapsedtime: Total execution time in milliseconds as an integer
    elapsedtime:总执行时间,以毫秒为单位,为整数
  • status: Keyword status as string PASS, FAIL, SKIP or NOT RUN. SKIP and NOT RUN are new in RF 4.0.
    status:关键字status为字符串PASSFAILSKIPNOT RUN跳过不运行是RF 4.0中的新功能。
log_message 日志信息 message 消息

Called when an executed keyword writes a log message.
当执行的关键字写入日志消息时调用。

message is a dictionary with the following contents:
message是一个字典,包含以下内容:

  • message: The content of the message.
    message:消息的内容。
  • level: Log level used in logging the message.
    level:记录消息时使用的日志级别
  • timestamp: Message creation time in format YYYY-MM-DD hh:mm:ss.mil.
    timestamp:消息创建时间,格式为YYYY-MM-DD hh:mm:ss.mil
  • html: String yes or no denoting whether the message should be interpreted as HTML or not.
    html:字符串yesno,表示消息是否应被解释为HTML。

Not called if the message level is below the current threshold level.
如果消息级别低于当前阈值级别,则不调用。

message 消息 message 消息

Called when the framework itself writes a syslog message.
当框架本身写入系统日志消息时调用。

message is a dictionary with the same contents as with log_message method.
message是一个字典,其内容与log_message方法相同。

library_import 库输入 name, attributes 名称,属性

Called when a library has been imported.
在导入库时调用。

name is the name of the imported library. If the library has been given a custom name when imported it using AS, name is the specified alias.
name是导入库的名称。如果库在使用AS导入时已被赋予自定义名称,则name是指定的别名。

Contents of the attribute dictionary:
属性字典的内容:

  • args: Arguments passed to the library as a list.
    args:以列表形式传递给库的参数。
  • originalname: The original library name if the library has been given an alias using AS, otherwise same as name.
    originalname:如果库已使用AS指定别名,则为原始库名称,否则与name相同。
  • source: An absolute path to the library source. None if getting the source of the library failed for some reason.
    source:指向库源的绝对路径。如果由于某种原因获取库的源失败,则无
  • importer: An absolute path to the file importing the library. None when BuiltIn is imported as well as when using the Import Library keyword.
    importer:导入库的文件的绝对路径。当导入BuiltIn以及使用Import Library关键字时,无
resource_import 资源_进口 name, attributes 名称,属性

Called when a resource file has been imported.
在导入资源文件时调用。

name is the name of the imported resource file without the file extension.
name是导入的资源文件的名称,不带文件扩展名。

Contents of the attribute dictionary:
属性字典的内容:

  • source: An absolute path to the imported resource file.
    source:导入的资源文件的绝对路径。
  • importer: An absolute path to the file importing the resource file. None when using the Import Resource keyword.
    importer:导入资源文件的文件的绝对路径。使用导入资源关键字时
variables_import 变量导入 name, attributes 名称,属性

Called when a variable file has been imported.
在导入变量文件时调用。

name is the name of the imported variable file with the file extension.
name是导入的变量文件的名称和文件扩展名。

Contents of the attribute dictionary:
属性字典的内容:

  • args: Arguments passed to the variable file as a list.
    args:以列表形式传递给变量文件的参数。
  • source: An absolute path to the imported variable file.
    source:导入变量文件的绝对路径。
  • importer: An absolute path to the file importing the resource file. None when using the Import Variables keyword.
    importer:导入资源文件的文件的绝对路径。使用Import Variables关键字时
output_file 输出文件 path 路径

Called when writing to an output file is ready.
当写入输出文件准备就绪时调用。

path is an absolute path to the file as a string.
path是一个字符串形式的文件的绝对路径。

log_file 日志文件 path 路径

Called when writing to a log file is ready.
当写入日志文件准备就绪时调用。

path is an absolute path to the file as a string.
path是一个字符串形式的文件的绝对路径。

report_file 报告文件 path 路径

Called when writing to a report file is ready.
当写入报表文件准备就绪时调用。

path is an absolute path to the file as a string.
path是一个字符串形式的文件的绝对路径。

xunit_file path 路径

Called when writing to an xunit file is ready.
当写入xunit文件准备就绪时调用。

path is an absolute path to the file as a string.
path是一个字符串形式的文件的绝对路径。

debug_file 调试文件 path 路径

Called when writing to a debug file is ready.
当写入调试文件准备就绪时调用。

path is an absolute path to the file as a string.
path是一个字符串形式的文件的绝对路径。

close 密切  

Called when the whole test execution ends.
在整个测试执行结束时调用。

With library listeners called when the library goes out of scope.
当库超出作用域时调用库侦听器

Listener version 3 第三版

Listener version 3 has mostly the same methods as listener version 2, but arguments of the methods related to test execution are different. These methods get actual running and result model objects that used by Robot Framework itself, and listeners can both query information they need and change the model objects on the fly.
监听器版本3与监听器版本2的方法基本相同,但与测试执行相关的方法参数不同。这些方法获取Robot Framework本身使用的实际运行和结果模型对象,侦听器既可以查询他们需要的信息,也可以动态地更改模型对象。

Listener version 3 was enhanced heavily in Robot Framework 7.0 when it got methods related to keywords and control structures. It still does not have methods related to library, resource file and variable file imports, but the plan is to add them in Robot Framework 7.1.
在Robot Framework 7.0中,当它获得与关键字和控制结构相关的方法时,它的版本3得到了很大的增强。它仍然没有与库,资源文件和变量文件导入相关的方法,但计划在Robot Framework 7.1中添加它们

Listener version 3 has separate methods for library keywords, user keywords and all control structures. If there is a need to listen to all keyword related events, it is possible to implement start_keyword and end_keyword. In addition to that, start_body_item and end_body_item can be implemented to get notifications related to all keywords and control structures. These higher level listener methods are not called if more specific methods like start_library_keyword or end_if are implemented.
SQL Server版本3对库关键字、用户关键字和所有控制结构都有单独的方法。如果需要监听所有与关键字相关的事件,可以实现start_keywordend_keyword。此外,可以实现start_body_itemend_body_item来获取与所有关键字和控制结构相关的通知。如果实现了start_library_keywordend_if等更具体的方法,则不会调用这些更高级别的侦听器方法。

Listener methods in the API version 3 are listed in the following table and in the API docs of the optional ListenerV3 base class.
下表和可选ListenerV3基类的API文档中列出了API版本3中的方法。

Methods in the listener API 3
监听器API中的方法3
Method 方法 Arguments 论点 Documentation 文件
start_suite 起始套件 data, result 数据、结果

Called when a test suite starts.
在测试套件启动时调用。

data and result are model objects representing the executed test suite and its execution results, respectively.
数据结果是分别表示所执行的测试套件及其执行结果的模型对象。

end_suite 尾套 data, result 数据、结果

Called when a test suite ends.
在测试套件结束时调用。

Same arguments as with start_suite.
start_suite相同的参数。

start_test 起动试验 data, result 数据、结果

Called when a test case starts.
在测试用例开始时调用。

data and result are model objects representing the executed test case and its execution results, respectively.
数据结果分别是表示所执行的测试用例及其执行结果的模型对象。

end_test 端部试验 data, result 数据、结果

Called when a test case ends.
在测试用例结束时调用。

Same arguments as with start_test.
start_test相同。

start_keyword data, result 数据、结果

Called when a keyword starts.
当关键字开始时调用。

data and result are model objects representing the executed keyword call and its execution results, respectively.
数据结果是分别表示所执行的关键字调用及其执行结果的模型对象。

This method is called, by default, with user keywords, library keywords and when a keyword call is invalid. It is not called if a more specific start_user_keyword, start_library_keyword or start_invalid_keyword method is implemented.
默认情况下,使用用户关键字、库关键字以及在关键字调用无效时调用此方法。如果实现了更具体的start_user_keywordstart_library_keywordstart_invalid_keyword方法,则不会调用该函数。

end_keyword 结束关键字 data, result 数据、结果

Called when a keyword ends.
当关键字结束时调用。

Same arguments and other semantics as with start_keyword.
start_keyword相同的参数和其他语义。

start_user_keyword 启动用户关键字 data, implementation, result
数据、实施、结果

Called when a user keyword starts.
当用户关键字开始时调用。

data and result are the same as with start_keyword and implementation is the actually executed user keyword.
dataresultstart_keyword相同,implementation是实际执行的user关键字

If this method is implemented, start_keyword is not called with user keywords.
如果实现此方法,则不会使用用户关键字调用start_keyword

end_user_keyword 最终用户关键字 data, implementation, result
数据、实施、结果

Called when a user keyword ends.
当用户关键字结束时调用。

Same arguments and other semantics as with start_user_keyword.
start_user_keyword相同的参数和其他语义。

start_library_keyword 启动库关键字 data implementation, result
数据实施,结果

Called when a library keyword starts.
在库关键字开始时调用。

data and result are the same as with start_keyword and implementation represents the executed library keyword.
dataresultstart_keyword相同,implementation表示执行的库关键字

If this method is implemented, start_keyword is not called with library keywords.
如果实现此方法,则不会使用库关键字调用start_keyword

end_library_keyword 结束库关键字 data, implementation, result
数据、实施、结果

Called when a library keyword ends.
当库关键字结束时调用。

Same arguments and other semantics as with start_library_keyword.
start_library_keyword相同的参数和其他语义。

start_invalid_keyword 起始无效关键字 data implementation, result
数据实施,结果

Called when an invalid keyword call starts.
当无效的关键字调用开始时调用。

data and result are the same as with start_keyword and implementation represents the invalid keyword call. Keyword may not have been found, there could have been multiple matches, or the keyword call itself could have been invalid.
dataresultstart_keyword相同,implementation表示无效的关键字调用。关键字可能未找到,可能存在多个匹配项,或者关键字调用本身可能无效。

If this method is implemented, start_keyword is not called with invalid keyword calls.
如果实现此方法,则不会使用无效的关键字调用来调用start_keyword

end_invalid_keyword 结束无效关键字 data, implementation, result
数据、实施、结果

Called when an invalid keyword call ends.
当无效的关键字调用结束时调用。

Same arguments and other semantics as with start_invalid_keyword.
start_invalid_keyword相同的参数和其他语义。

start_for, start_for_iteration, start_while, start_while_iteration, start_if, start_if_branch, start_try, start_try_branch, start_var, start_continue, start_break, start_return
start_for,start_for_iteration,start_while,start_while_iteration,start_if,start_if_分支,start_try,start_try_分支,start_var,start_continue,start_break,start_return
data, result 数据、结果

Called when control structures start.
在控制结构启动时调用。

See the documentation and type hints of the optional ListenerV3 base class for more information.
有关更多信息,请参见可选ListenerV3基类的文档和类型提示。

end_for, end_for_iteration, end_while, end_while_iteration, end_if, end_if_branch, end_try, end_try_branch, end_var, end_continue, end_break, end_return
end_for,end_for_iteration,end_while,end_while_iteration,end_if,end_if_分支,end_try,end_try_分支,end_var,end_continue,end_break,end_return
data, result 数据、结果

Called when control structures end.
当控制结构结束时调用。

See the documentation and type hints of the optional ListenerV3 base class for more information.
有关更多信息,请参见可选ListenerV3基类的文档和类型提示。

start_error 起动误差 data, result 数据、结果 Called when invalid syntax starts.
在无效语法开始时调用。
end_error 末端误差 data, result 数据、结果 Called when invalid syntax ends.
在无效语法结束时调用。
start_body_item 起始体项 data, result 数据、结果 Called when a keyword or a control structure starts, unless a more specific method such as start_keyword or start_if is implemented.
在关键字或控制结构启动时调用,除非实现了更具体的方法,如start_keywordstart_if
end_body_item 结束体项 data, result 数据、结果 Called when a keyword or a control structure ends, unless a more specific method such as end_keyword or end_if is implemented.
当关键字或控制结构结束时调用,除非实现了更具体的方法,如end_keywordend_if
log_message 日志信息 message 消息

Called when an executed keyword writes a log message. message is a model object representing the logged message.
当执行的关键字写入日志消息时调用。message是一个模型对象,表示记录的消息

This method is not called if the message has level below the current threshold level.
如果消息的级别低于当前阈值级别,则不调用此方法。

message 消息 message 消息

Called when the framework itself writes a syslog message.
当框架本身写入系统日志消息时调用。

message is same object as with log_message.
messagelog_message是同一个对象。

library_import 库输入 N/A Not currently implemented.
目前尚未执行。
resource_import 资源_进口 N/A Not currently implemented.
目前尚未执行。
variables_import 变量导入 N/A Not currently implemented.
目前尚未执行。
output_file 输出文件 path 路径

Called when writing to an output file is ready.
当写入输出文件准备就绪时调用。

path is an absolute path to the file as a pathlib.Path object.
path是作为pathlib.Path对象的文件的绝对路径。

log_file 日志文件 path 路径

Called when writing to a log file is ready.
当写入日志文件准备就绪时调用。

path is an absolute path to the file as a pathlib.Path object.
path是作为pathlib.Path对象的文件的绝对路径。

report_file 报告文件 path 路径

Called when writing to a report file is ready.
当写入报表文件准备就绪时调用。

path is an absolute path to the file as a pathlib.Path object.
path是作为pathlib.Path对象的文件的绝对路径。

xunit_file path 路径

Called when writing to an xunit file is ready.
当写入xunit文件准备就绪时调用。

path is an absolute path to the file as a pathlib.Path object.
path是作为pathlib.Path对象的文件的绝对路径。

debug_file 调试文件 path 路径

Called when writing to a debug file is ready.
当写入调试文件准备就绪时调用。

path is an absolute path to the file as a pathlib.Path object.
path是作为pathlib.Path对象的文件的绝对路径。

close 密切  

Called when the whole test execution ends.
在整个测试执行结束时调用。

With library listeners called when the library goes out of scope.
当库超出作用域时调用库侦听器

Note 注意

Prior to Robot Framework 7.0, paths passed to result file related listener version 3 methods were strings.
在Robot Framework 7.0之前,传递到结果文件相关侦听器版本3方法的路径是字符串。

4.3.3   Taking listeners into use
4.3.3使用监听器

Registering listeners from command line
从命令行注册侦听器

Listeners that need to be active during the whole execution must be taken into use from the command line. That is done using the --listener option so that the name of the listener is given to it as an argument. The listener name is got from the name of the class or module implementing the listener, similarly as library name is got from the class or module implementing the library. The specified listeners must be in the same module search path where test libraries are searched from when they are imported. In addition to registering a listener by using a name, it is possible to give an absolute or a relative path to the listener file similarly as with test libraries. It is possible to take multiple listeners into use by using this option several times:
在整个执行过程中需要活动的侦听器必须从命令行使用。这是使用--listener选项完成的,以便将侦听器的名称作为参数提供给它。监听器的名称是从实现监听器的类或模块的名称中获得的,类似于库的名称是从实现库的类或模块中获得的。指定的侦听器必须位于导入测试库时从中搜索测试库的同一模块搜索路径中。除了使用名称注册监听器之外,还可以提供监听器文件的绝对或相对路径,与测试库类似。通过多次使用此选项,可以使用多个侦听器:

robot --listener MyListener tests.robot
robot --listener path/to/MyListener.py tests.robot
robot --listener module.Listener --listener AnotherListener tests.robot

It is also possible to give arguments to listener classes from the command line. Arguments are specified after the listener name (or path) using a colon (:) as a separator. If a listener is given as an absolute Windows path, the colon after the drive letter is not considered a separator. Additionally, it is possible to use a semicolon (;) as an alternative argument separator. This is useful if listener arguments themselves contain colons, but requires surrounding the whole value with quotes on UNIX-like operating systems:
也可以从命令行向侦听器类提供参数。参数在监听器名称(或路径)后面指定,使用冒号()作为分隔符。如果侦听器作为绝对Windows路径给出,则驱动器号后的冒号不被视为分隔符。此外,还可以使用一个分隔符(;)作为替代参数分隔符。如果侦听器参数本身包含冒号,这很有用,但在类UNIX操作系统上需要用引号将整个值括起来:

robot --listener listener.py:arg1:arg2 tests.robot
robot --listener "listener.py;arg:with:colons" tests.robot
robot --listener c:\path\listener.py;d:\first\arg;e:\second\arg tests.robot

In addition to passing arguments one-by-one as positional arguments, it is possible to pass them using the named argument syntax similarly as when using keywords:
除了将参数作为位置参数逐个传递之外,还可以使用命名参数语法传递它们,与使用关键字时类似:

robot --listener listener.py:name=value tests.robot
robot --listener "listener.py;name=value:with:colons;second=argument" tests.robot

Listener arguments are automatically converted using same rules as with keywords based on type hints and default values. For example, this listener
使用基于类型提示默认值的关键字相同的规则自动转换SQL参数。例如,此侦听器

class Listener:

    def __init__(self, port: int, log=True):
        self.port = post
        self.log = log

could be used like 可以用来

robot --listener Listener:8270:false

and the first argument would be converted to an integer based on the type hint and the second to a Boolean based on the default value.
第一个参数将根据类型提示转换为整数,第二个参数将根据默认值转换为布尔值。

Note 注意

Both the named argument syntax and argument conversion are new in Robot Framework 4.0.
命名参数语法和参数转换都是Robot Framework 4.0中的新功能。

Libraries as listeners 图书馆作为听众

Sometimes it is useful also for test libraries to get notifications about test execution. This allows them, for example, to perform certain clean-up activities automatically when a test suite or the whole test execution ends.
有时候,测试库获取有关测试执行的通知也很有用。例如,这允许他们在测试套件或整个测试执行结束时自动执行某些清理活动。

Registering listener 正在注册监听程序

A test library can register a listener by using the ROBOT_LIBRARY_LISTENER attribute. The value of this attribute should be an instance of the listener to use. It may be a totally independent listener or the library itself can act as a listener. To avoid listener methods to be exposed as keywords in the latter case, it is possible to prefix them with an underscore. For example, instead of using end_suite it is possible to use _end_suite.
测试库可以使用ROBOT_LIBRARY_LISTENER属性注册侦听器。此属性的值应该是要使用的侦听器的实例。它可以是一个完全独立的侦听器,或者库本身可以充当侦听器。在后一种情况下,为了避免侦听器方法被公开为关键字,可以在它们前面加上下划线。例如,可以使用_end_suite代替end_suite。

Following examples illustrates using an external listener as well as a library acting as a listener itself:
以下示例说明了如何使用外部侦听器以及充当侦听器本身的库:

from listener import Listener


class LibraryWithExternalListener:
    ROBOT_LIBRARY_SCOPE = 'GLOBAL'
    ROBOT_LIBRARY_LISTENER = Listener()

    def example_keyword(self):
         ...
class LibraryItselfAsListener:
    ROBOT_LIBRARY_SCOPE = 'SUITE'
    ROBOT_LISTENER_API_VERSION = 2

    def __init__(self):
        self.ROBOT_LIBRARY_LISTENER = self

    # Use the '_' prefix to avoid listener method becoming a keyword.
    def _end_suite(self, name, attrs):
        print(f"Suite '{name}' ending with status {attrs['id']}.")

    def example_keyword(self):
         ...

As the second example above already demonstrated, library listeners can specify listener interface versions using the ROBOT_LISTENER_API_VERSION attribute exactly like any other listener.
正如上面的第二个示例所演示的,库侦听器可以使用ROBOT_LISTENER_API_VERSION属性指定侦听器接口版本,就像任何其他侦听器一样。

Starting from Robot Framework 7.0, a listener can register itself to be a listener also by using a string SELF (case-insensitive) as a listener. This is especially convenient when using the @library decorator:
从Robot Framework 7.0开始,侦听器也可以通过使用字符串SELF(不区分大小写)作为侦听器来注册自己为侦听器。这在使用@library装饰器时特别方便:

from robot.api.deco import keyword, library


@library(scope='SUITE', listener='SELF')
class LibraryItselfAsListener:

    # Listener version is not specified, so uses the listener version 3 by default.
    # When using the @library decorator, keywords must use the @keyword decorator,
    # so there is no need to use the '_' prefix here.
    def end_suite(self, data, result):
        print(f"Suite '{data.name}' ending with status {result.status}.")

    @keyword
    def example_keyword(self):
         ...

It is also possible to specify multiple listeners for a single library by giving ROBOT_LIBRARY_LISTENER a value as a list:
也可以通过给ROBOT_LIBRARY_LISTENER一个值作为列表来为单个库指定多个侦听器:

from listeners import Listener1, Listener2, Listener3


class LibraryWithMultipleListeners:
    ROBOT_LIBRARY_LISTENER = [Listener1(), Listener2(), Listener3()]

    def example_keyword(self):
         ...
Called listener methods 调用侦听器方法

Library listeners get notifications about all events in suites where libraries using them are imported. In practice this means that suite, test, keyword, control structure and log message related methods are called. In addition to them, the close method is called when the library goes out of the scope.
库侦听器在导入使用它们的库的套件中获得有关所有事件的通知。在实践中,这意味着套件,测试,关键字,控制结构和日志消息相关的方法被调用。除了它们之外,当库超出范围时还会调用close方法。

If library creates a new listener instance every time when the library itself is instantiated, the actual listener instance to use will change according to the library scope.
如果库在每次实例化库本身时都创建一个新的侦听器实例,则要使用的实际侦听器实例将根据库作用域而变化。

4.3.4   Listener examples 4.3.4实例

This section contains examples using the listener interface. First examples illustrate getting notifications durin execution and latter examples modify executed tests and created results.
本节包含使用侦听器接口的示例。第一个例子说明了在执行过程中获取通知,后面的例子修改了执行的测试和创建的结果。

Getting information 获取信息

The first example is implemented as a Python module. It uses the listener version 2, but could equally well be implemented by using the listener version 3.
第一个例子是作为Python模块实现的。它使用侦听器版本2,但也可以使用侦听器版本3来实现。

"""Listener that stops execution if a test fails."""

ROBOT_LISTENER_API_VERSION = 2

def end_test(name, attrs):
    if attrs['status'] == 'FAIL':
        print(f"Test '{name}'" failed: {attrs['message']}")
        input("Press enter to continue.")

If the above example would be saved to, for example, PauseExecution.py file, it could be used from the command line like this:
如果上面的示例将保存到例如PauseExecution.py文件中,则可以从命令行使用它,如下所示:

robot --listener path/to/PauseExecution.py tests.robot

The next example, which still uses the listener version 2, is slightly more complicated. It writes all the information it gets into a text file in a temporary directory without much formatting. The filename may be given from the command line, but it also has a default value. Note that in real usage, the debug file functionality available through the command line option --debugfile is probably more useful than this example.
下一个示例仍然使用侦听器版本2,稍微复杂一些。它将获得的所有信息写入临时目录中的文本文件中,而无需进行太多格式化。文件名可以从命令行给出,但它也有一个默认值。请注意,在真实的使用中,通过命令行选项--debugfile提供的调试文件功能可能比本例更有用。

import os.path
import tempfile


class Example:
    ROBOT_LISTENER_API_VERSION = 2

    def __init__(self, file_name='listen.txt'):
        path = os.path.join(tempfile.gettempdir(), file_name)
        self.file = open(path, 'w')

    def start_suite(self, name, attrs):
        self.file.write("%s '%s'\n" % (name, attrs['doc']))

    def start_test(self, name, attrs):
        tags = ' '.join(attrs['tags'])
        self.file.write("- %s '%s' [ %s ] :: " % (name, attrs['doc'], tags))

    def end_test(self, name, attrs):
        if attrs['status'] == 'PASS':
            self.file.write('PASS\n')
        else:
            self.file.write('FAIL: %s\n' % attrs['message'])

    def end_suite(self, name, attrs):
         self.file.write('%s\n%s\n' % (attrs['status'], attrs['message']))

    def close(self):
         self.file.close()

Modifying data and results
修改数据和结果

The following examples illustrate how to modify the executed tests and suites as well as the execution results. All these examples require using the listener version 3.
以下示例说明了如何修改已执行的测试和套件以及执行结果。所有这些示例都需要使用侦听器版本3

Modifying executed suites and tests
修改已执行的套件和测试

Changing what is executed is as easy as modifying the model objects representing executed data passed to listener methods. This is illustrated by the example below that adds a new test to each executed suite and a new keyword call to each test.
更改执行的内容就像修改表示传递给侦听器方法的已执行数据的模型对象一样简单。下面的示例说明了这一点,该示例向每个已执行的套件添加一个新的测试,并向每个测试添加一个新的关键字调用。

def start_suite(data, result):
    data.tests.create(name='New test')

def start_test(data, result):
    data.body.create_keyword(name='Log', args=['Keyword added by listener!'])

This API is very similar to the pre-run modifier API that can be used to modify suites and tests before the whole test execution starts. The main benefit of using the listener API is that modifications can be done dynamically based on execution results or otherwise. This allows, for example, interesting possibilities for model based testing.
这个API与运行前修改器API非常相似,后者可用于在整个测试执行开始之前修改套件和测试。使用侦听器API的主要好处是可以根据执行结果或其他情况动态地进行修改。例如,这允许基于模型的测试的有趣的可能性。

Although the listener interface is not built on top of Robot Framework's internal visitor interface similarly as the pre-run modifier API, listeners can still use the visitors interface themselves. For example, the SelectEveryXthTest visitor used in pre-run modifier examples could be used like this:
虽然侦听器接口不是像预运行修改器API那样构建在Robot Framework的内部访问者接口之上,但侦听器仍然可以自己使用访问者接口。例如,在预运行修饰符示例中使用的SelectEveryXthTest访问者可以这样使用:

from SelectEveryXthTest import SelectEveryXthTest


def start_suite(suite, result):
    selector = SelectEveryXthTest(x=2)
    suite.visit(selector)
Accessing library or resource file
存储库或资源文件

It is possible to get more information about the actually executed keyword and the library or resource file it belongs to:
可以获得有关实际执行的关键字及其所属的库或资源文件的更多信息:

from robot.running import Keyword as KeywordData, LibraryKeyword
from robot.result import Keyword as KeywordResult


def start_library_keyword(data: KeywordData,
                          implementation: LibraryKeyword,
                          result: KeywordResult):
    library = implementation.owner
    print(f"Keyword '{implementation.name}' is implemented in library "
          f"'{library.name}' at '{implementation.source}' on line "
          f"{implementation.lineno}. The library has {library.scope.name} "
          f"scope and the current instance is {library.instance}.")

As the above example illustrates, it is possible to get an access to the actual library instance. This means that listeners can inspect the library state and also modify it. With user keywords it is even possible to modify the keyword itself or, via the owner resource file, any other keyword in the resource file.
如上面的例子所示,可以访问实际的库实例。这意味着侦听器可以检查库状态并修改它。使用用户关键字,甚至可以修改关键字本身,或者通过所有者资源文件修改资源文件中的任何其他关键字。

Modifying results 修改结果

Test execution results can be altered by modifying the result objects passed to listener methods. This is demonstrated by the following listener that is implemented as a class and also uses type hints:
测试执行结果可以通过修改传递给侦听器方法的结果对象来更改。下面的侦听器演示了这一点,该侦听器实现为类,并且还使用类型提示:

from robot import result, running


class ResultModifier:

    def __init__(self, max_seconds: float = 10.0):
        self.max_seconds = max_seconds

    def start_suite(self, data: running.TestSuite, result: result.TestSuite):
        result.doc = 'Documentation set by listener.'
        # Information about tests only available via data at this point.
        smoke_tests = [test for test in data.tests if 'smoke' in test.tags]
        result.metadata['Smoke tests'] = len(smoke_tests)

    def end_test(self, data: running.TestCase, result: result.TestCase):
        elapsed_seconds = result.elapsed_time.total_seconds()
        if result.status == 'PASS' and  elapsed_seconds > self.max_milliseconds:
            result.status = 'FAIL'
            result.message = 'Test execution took too long.'

    def log_message(self, msg: result.Message):
        if msg.level == 'WARN' and not msg.html:
            msg.message = f'<b style="font-size: 1.5em">{msg.message}</b>'
            msg.html = True

A limitation is that modifying the name of the current test suite or test case is not possible because it has already been written to the output.xml file when listeners are called. Due to the same reason modifying already finished tests in the end_suite method has no effect either.
一个限制是,修改当前测试套件或测试用例的名称是不可能的,因为在调用侦听器时,它已经被写入到output.xml文件中。由于同样的原因,在end_suite方法中修改已经完成的测试也没有效果。

Notice that although listeners can change status of any executed keyword or control structure, that does not directly affect the status of the executed test. In general listeners cannot directly fail keywords so that execution would stop or handle failures so that execution would continue. This kind of functionality may be added in the future if there are needs.
请注意,尽管侦听器可以更改任何已执行关键字或控制结构的状态,但这并不直接影响已执行测试的状态。一般来说,侦听器不能直接使关键字失败以使执行停止,也不能处理失败以使执行继续。如果有需要,将来可能会增加这种功能。

This API is very similar to the pre-Rebot modifier API that can be used to modify results before report and log are generated. The main difference is that listeners modify also the created output.xml file.
此API非常类似于Rebot前修改器API,可用于在生成报告和日志之前修改结果。主要的区别是侦听器还修改创建的output.xml文件。

More examples 多个示例

Keyword and control structure related listener version 3 methods are so versatile that covering them fully here in the User Guide is not possible. For more examples, you can see the acceptance tests using theses methods in various ways.
关键字和控制结构相关的侦听器版本3方法是如此通用,在用户指南中完全涵盖它们是不可能的。更多的例子,你可以看到验收测试使用这些方法以各种方式。

4.4   Parser interface 4.4解析器接口

Robot Framework supports external parsers that can handle custom data formats or even override Robot Framework's own parser.
Robot Framework支持外部解析器,这些解析器可以处理自定义数据格式,甚至可以覆盖Robot Framework自己的解析器。

Note 注意

Custom parsers are new in Robot Framework 6.1.
自定义解析器是Robot Framework 6.1中的新功能。

4.4.1   Taking parsers into use
4.4.1使用解析器

Parsers are taken into use from the command line with the --parser option using exactly the same semantics as with listeners. This includes specifying parsers as names or paths, giving arguments to parser classes, and so on:
使用--parser选项可以从命令行使用解析器,其语义与使用侦听器完全相同。这包括将解析器指定为名称或路径,为解析器类提供参数,等等:

robot --parser MyParser tests.custom
robot --parser path/to/MyParser.py tests.custom
robot --parser Parser1:arg --parser Parser2:a1:a2 path/to/tests

4.4.2   Parser API 4.4.2解析器API

Parsers can be implemented both as modules and classes. This section explains what attributes and methods they must contain.
解析器可以实现为模块和类。本节解释它们必须包含哪些属性和方法。

EXTENSION or extension attribute
EXTENSION扩展属性

This attribute specifies what file extension or extensions the parser supports. Both EXTENSION and extension names are accepted, and the former has precedence if both exist. The attribute can be either a string or a sequence of strings. Extensions are case-insensitive and can be specified with or without the leading dot. If a parser is implemented as a class, it is possible to set this attribute either as a class attribute or as an instance attribute.
此属性指定解析器支持的文件扩展名。EXTENSION扩展名都被接受,如果两者都存在,则前者优先。属性可以是字符串或字符串序列。扩展名不区分大小写,可以使用或不使用前导点指定。如果解析器是作为类实现的,则可以将此属性设置为类属性或实例属性。

Also extensions containing multiple parts like .example.ext or .robot.zip are supported.
也支持包含多个部分的扩展名,如. example.ext. robot.zip

Note 注意

If a parser supports the .robot extension, it will be used for parsing these files instead of the standard parser.
如果解析器支持.robot扩展名,则将使用它来解析这些文件,而不是标准解析器。

parse method
parse方法

The mandatory parse method is responsible for parsing suite files. It is called with each parsed file that has an extension that the parser supports. The method must return a TestSuite object.
强制解析方法负责解析套件文件。对于每个具有解析器支持的扩展名的解析文件,都会调用该函数。方法必须返回TestSuite对象。

In simple cases parse can be implemented so that it accepts just a single argument that is a pathlib.Path object pointing to the file to parse. If the parser is interested in defaults for Test Setup, Test Teardown, Test Tags and Test Timeout set in higher level suite initialization files, the parse method must accept two arguments. In that case the second argument is a TestDefaults object.
在简单的情况下,可以实现parse,使其只接受一个参数,即指向要解析的文件的pathlib.Path对象。如果解析器对更高级别套件初始化文件中的测试设置测试拆卸测试标记测试标记集的默认值感兴趣,则解析方法必须接受两个参数。在这种情况下,第二个参数是一个测试对象。

parse_init method
parse_init方法

The optional parse_init method is responsible for parsing suite initialization files i.e. files in format __init__.ext where .ext is an extension supported by the parser. The method must return a TestSuite object representing the whole directory. Suites created from child suite files and directories will be added to its child suites.
可选的parse_init方法负责解析套件初始化文件,即格式为__init__.ext的文件,其中.ext是解析器支持的扩展名。该方法必须返回一个表示整个目录的TestSuite对象。从子套件文件和目录创建的套件将添加到其子套件中。

Also parse_init can be implemented so that it accepts one or two arguments, depending on is it interested in test related default values or not. If it accepts defaults, it can manipulate the passed TestDefaults object and changes are seen when parsing child suite files.
还可以实现parse_init,以便它接受一个或两个参数,具体取决于它是否对测试相关的默认值感兴趣。如果它接受默认值,它就可以操作传递的TestData对象,并且在解析子套件文件时可以看到更改。

This method is only needed if a parser needs to support suite initialization files.
只有当解析器需要支持套件初始化文件时,才需要此方法。

Optional base class 可选基类

Parsers do not need to implement any explicit interface, but it may be helpful to extend the optional Parser base class. The main benefit is that the base class has documentation and type hints. It also works as a bit more formal API specification.
解析器不需要实现任何显式接口,但是扩展可选的Parser基类可能会有所帮助。主要的好处是基类有文档和类型提示。它也可以作为一个更正式的API规范。

4.4.3   Examples 4.4.3示例

Parser implemented as module
作为模块实现的解析器

The first example demonstrates a simple parser implemented as a module and supporting one hard-coded extension. It just creates a dummy suite and does not actually parse anything.
第一个示例演示了一个简单的解析器,该解析器实现为一个模块,并支持一个硬编码的扩展。它只是创建了一个虚拟套件,并没有真正解析任何东西。

from robot.api import TestSuite


EXTENSION = '.example'


def parse(source):
    suite = TestSuite(name='Example', source=source)
    test = suite.tests.create(name='Test')
    test.body.create_keyword(name='Log', args=['Hello!'])
    return suite

Parser implemented as class
解析器实现为类

The second parser is implemented as a class that accepts the extension to use as an argument. The parser reads the given source file and creates dummy tests from each line it contains.
第二个解析器是作为一个类实现的,它接受扩展作为参数使用。解析器读取给定的源文件,并从它包含的每一行创建虚拟测试。

from pathlib import Path
from robot.api import TestSuite


class ExampleParser:

    def __init__(self, extension: str):
        self.extension = extension

    def parse(self, source: Path) -> TestSuite:
        name = TestSuite.name_from_source(source, self.extension)
        suite = TestSuite(name, source=source)
        for line in source.read_text().splitlines():
            test = suite.tests.create(name=line)
            test.body.create_keyword(name='Log', args=['Hello!'])
        return suite

Parser extending optional base class
解析器扩展可选基类

This parser extends the optional Parser base class. It supports parsing suite initialization files, uses TestDefaults and registers multiple extensions.
这个解析器扩展了可选的Parser基类。它支持解析套件初始化文件,使用Teststack并注册多个扩展。

from pathlib import Path
from robot.api import TestSuite
from robot.api.interfaces import Parser, TestDefaults


class ExampleParser(Parser):
    extension = ('example', 'another')

    def parse(self, source: Path, defaults: TestDefaults) -> TestSuite:
        """Create a suite and set possible defaults from init files to tests."""
        suite = TestSuite(TestSuite.name_from_source(source), source=source)
        for line in source.read_text().splitlines():
            test = suite.tests.create(name=line, doc='Example')
            test.body.create_keyword(name='Log', args=['Hello!'])
            defaults.set_to(test)
        return suite

    def parse_init(self, source: Path, defaults: TestDefaults) -> TestSuite:
        """Create a dummy suite and set some defaults.

        This method is called only if there is an initialization file with
        a supported extension.
        """
        defaults.tags = ('tags', 'from init')
        defaults.setup = {'name': 'Log', 'args': ['Hello from init!']}
        return TestSuite(TestSuite.name_from_source(source.parent), doc='Example',
                         source=source, metadata={'Example': 'Value'})

Parser as preprocessor 解析器作为预处理器

The final example parser acts as a preprocessor for Robot Framework data files that supports headers in format === Test Cases === in addition to *** Test Cases ***. In this kind of usage it is convenient to use TestSuite.from_string, TestSuite.from_model and TestSuite.from_file_system factory methods for constructing the returned suite.
最后一个示例解析器充当Robot Framework数据文件的预处理器,除了* Test Cases * 之外,它还支持格式为= Test Cases =的头。在这种用法中,使用TestSuite.from_stringTestSuite.from_modelTestSuite.from_file_system工厂方法来构造返回的套件是很方便的。

from pathlib import Path
from robot.running import TestDefaults, TestSuite


class RobotPreprocessor:
    extension = '.robot'

    def parse(self, source: Path, defaults: TestDefaults) -> TestSuite:
        data = source.read_text()
        for header in 'Settings', 'Variables', 'Test Cases', 'Keywords':
            data = data.replace(f'=== {header} ===', f'*** {header} ***')
        suite = TestSuite.from_string(data, defaults=defaults)
        return suite.config(name=TestSuite.name_from_source(source), source=source)

5   Supporting Tools 5支持工具

5.1   Library documentation tool (Libdoc)
5.1图书馆文档工具(Libdoc)

Libdoc is Robot Framework's built-in tool that can generate documentation for Robot Framework libraries and resource files. It can generate HTML documentation for humans as well as machine readable spec files in XML and JSON formats. Libdoc also has few special commands to show library or resource information on the console.
Libdoc是Robot Framework的内置工具,可以为Robot Framework库和资源文件生成文档。它可以为人类生成HTML文档,也可以生成XML和JSON格式的机器可读规范文件。Libdoc也有一些特殊的命令来在控制台上显示库或资源信息。

Documentation can be created for:
可以为以下项目创建文档:

Additionally it is possible to use XML and JSON spec files created by Libdoc earlier as an input.
此外,还可以使用Libdoc之前创建的XML和JSON规范文件作为输入。

Note 注意

Support for generating documentation for suite files and suite initialization files is new in Robot Framework 6.0.
支持为套件文件和套件初始化文件生成文档是Robot Framework 6.0中的新功能。

Note 注意

The support for the JSON spec files is new in Robot Framework 4.0.
对JSON规范文件的支持是Robot Framework 4.0中的新功能。

5.1.1   General usage 5.1.1一般用法

Synopsis 概要

libdoc [options] library_or_resource output_file
libdoc [options] library_or_resource list|show|version [names]

Options 选项

-f, --format <html|xml|json|libspec>
 Specifies whether to generate an HTML output for humans or a machine readable spec file in XML or JSON format. The libspec format means XML spec with documentations converted to HTML. The default format is got from the output file extension.
指定是生成供人使用的HTML输出,还是生成XML或JSON格式的机器可读规范文件。libspec格式意味着文档转换为HTML的XML规范。默认格式是从输出文件扩展名获得的。
-s, --specdocformat <raw|html>
 Specifies the documentation format used with XML and JSON spec files. raw means preserving the original documentation format and html means converting documentation to HTML. The default is raw with XML spec files and html with JSON specs and when using the special libspec format. New in Robot Framework 4.0.
指定与XML和JSON规范文件一起使用的文档格式。raw表示保留原始文档格式,html表示将文档转换为HTML。当使用特殊的libspec格式时,默认值是raw(带有XML规范文件)和html(带有JSON规范)。机器人框架4.0中的新功能。
-F, --docformat <robot|html|text|rest>
 Specifies the source documentation format. Possible values are Robot Framework's documentation format, HTML, plain text, and reStructuredText. Default value can be specified in test library source code and the initial default value is robot.
指定源文档格式。可能的值是Robot Framework的文档格式、HTML、纯文本和reStructuredText。可以在测试库源代码中指定默认值,初始默认值为robot
--theme <dark|light|none>
 Use dark or light HTML theme. If this option is not used, or the value is none, the theme is selected based on the browser color scheme. Only applicable with HTML outputs. New in Robot Framework 6.0.
使用深色或浅色HTML主题。如果未使用此选项,或者值为“无”,则将根据浏览器配色方案选择主题。仅适用于HTML输出。机器人框架6.0中的新功能。
-N, --name <newname>
 Sets the name of the documented library or resource.
设置文档库或资源的名称。
-V, --version <newversion>
 Sets the version of the documented library or resource. The default value for test libraries is defined in the source code.
设置文档库或资源的版本。测试库的默认值在源代码中定义
-P, --pythonpath <path>
 Additional locations where to search for libraries and resources similarly as when running tests.
用于搜索库和资源的其他位置,与运行测试时类似。
--quiet Do not print the path of the generated output file to the console. New in Robot Framework 4.0.
不要将生成的输出文件的路径打印到控制台。机器人框架4.0中的新功能。
-h, --help Prints this help. 打印此帮助。

Executing Libdoc 执行Libdoc

The easiest way to run Libdoc is using the libdoc command created as part of the normal installation:
运行Libdoc最简单的方法是使用作为正常安装的一部分创建的libdoc命令:

libdoc ExampleLibrary ExampleLibrary.html

Alternatively it is possible to execute the robot.libdoc module directly. This approach is especially useful if you have installed Robot Framework using multiple Python versions and want to use a specific version with Libdoc:
或者也可以直接执行robot.libdoc模块。如果您已经使用多个Python版本安装了Robot Framework,并且希望在Libdoc中使用特定版本,则此方法特别有用:

python -m robot.libdoc ExampleLibrary ExampleLibrary.html
python3.9 -m robot.libdoc ExampleLibrary ExampleLibrary.html

Yet another alternative is running the robot.libdoc module as a script:
还有一种方法是将robot.libdoc模块作为脚本运行:

python path/to/robot/libdoc.py ExampleLibrary ExampleLibrary.html

Note 注意

The separate libdoc command is new in Robot Framework 4.0.
单独的libdoc命令是Robot Framework 4.0中的新功能。

Specifying library or resource file
存储库或资源文件

Python libraries and dynamic libraries with name or path
带有名称或路径的Python库和动态库

When documenting libraries implemented with Python or that use the dynamic library API, it is possible to specify the library either by using just the library name or path to the library source code:
当记录使用Python实现的库或使用动态库API的库时,可以通过仅使用库名称或库源代码的路径来指定库:

libdoc ExampleLibrary ExampleLibrary.html
libdoc src/ExampleLibrary.py docs/ExampleLibrary.html

In the former case the library is searched using the module search path and its name must be in the same format as when importing libraries in Robot Framework test data.
在前一种情况下,使用模块搜索路径搜索库,并且其名称的格式必须与在Robot Framework测试数据中导入库时的格式相同。

If these libraries require arguments when they are imported, the arguments must be catenated with the library name or path using two colons like MyLibrary::arg1::arg2. If arguments change what keywords the library provides or otherwise alter its documentation, it might be a good idea to use --name option to also change the library name accordingly.
如果这些库在导入时需要参数,则必须使用两个冒号(如MyLibrary::arg 1::arg 2)将参数与库名称或路径连接起来。如果参数更改了库提供的关键字或更改了它的文档,那么使用--name选项来相应地更改库名称可能是一个好主意。

Resource files with path 具有路径的资源文件

Resource files must always be specified using a path:
必须始终使用路径指定资源文件:

libdoc example.resource example.html

If the path does not exist, resource files are also searched from all directories in the module search path similarly as when executing test cases.
如果路径不存在,则还将从模块搜索路径中的所有目录中搜索资源文件,这与执行测试用例时的情况类似。

Libdoc spec files Libdoc规范文件

Earlier generated Libdoc XML or JSON spec files can also be used as inputs. This works if spec files use either *.xml, *.libspec or *.json extension:
早期生成的Libdoc XML或JSON规范文件也可以用作输入。如果spec文件使用*.xml*.libspec*.json扩展名,则此方法有效:

libdoc Example.xml Example.html
libdoc Example.libspec Example.html
libdoc Example.json Example.html

Note 注意

Support for the *.libspec extension is new in Robot Framework 3.2.
*.libspec扩展名的支持是Robot Framework 3.2中的新功能。

Note 注意

Support for the *.json extension is new in Robot Framework 4.0.
*.json扩展名的支持是Robot Framework 4.0中的新功能。

Generating documentation 生成文档

Libdoc can generate documentation in HTML (for humans) and XML or JSON (for tools) formats. The file where to write the documentation is specified as the second argument after the library/resource name or path, and the output format is got from the output file extension by default.
Libdoc可以生成HTML(用于人类)和XML或JSON(用于工具)格式的文档。在库/资源名称或路径之后的第二个参数中指定要编写文档的文件,默认情况下,输出格式从输出文件扩展名获得。

Libdoc HTML documentation
Libdoc HTML文档

Most Robot Framework libraries use Libdoc to generate library documentation in HTML format. This format is thus familiar for most people who have used Robot Framework. A simple example can be seen below, and it has been generated based on the example found a bit later in this section.
大多数Robot Framework库使用Libdoc生成HTML格式的库文档。因此,这种格式对于大多数使用过Robot Framework的人来说都很熟悉。下面是一个简单的示例,它是基于本节后面的示例生成的。

src/SupportingTools/ExampleLibrary.png

The HTML documentation starts with general library introduction, continues with a section about configuring the library when it is imported (when applicable), and finally has shortcuts to all keywords and the keywords themselves. The magnifying glass icon on the lower right corner opens the keyword search dialog that can also be opened by simply pressing the s key.
HTML文档从一般的库介绍开始,接着是关于在导入库时配置库的部分(如果适用),最后是所有关键字和关键字本身的快捷方式。右下角的放大镜图标打开关键字搜索对话框,也可以通过简单地按s键打开。

Libdoc automatically creates HTML documentation if the output file extension is *.html. If there is a need to use some other extension, the format can be specified explicitly with the --format option.
如果输出文件扩展名为*.html,Libdoc会自动创建HTML文档。如果需要使用其他扩展名,可以使用--format选项显式指定格式。

libdoc OperatingSystem OperatingSystem.html
libdoc --name MyLibrary Remote::http://10.0.0.42:8270 MyLibrary.html
libdoc --format HTML test/resource.robot doc/resource.htm
Libdoc XML spec files Libdoc XML规范文件

Libdoc can also generate documentation in XML format that is suitable for external tools such as editors. It contains all the same information as the HTML format but in a machine readable format.
Libdoc还可以生成XML格式的文档,适用于编辑器等外部工具。它包含与HTML格式相同的所有信息,但采用机器可读格式。

XML spec files also contain library and keyword source information so that the library and each keyword can have source path (source attribute) and line number (lineno attribute). The source path is relative to the directory where the spec file is generated thus does not refer to a correct file if the spec is moved. The source path is omitted with keywords if it is the same as with the library, and both the source path and the line number are omitted if getting them from the library fails for whatever reason.
XML规范文件还包含库和关键字源信息,以便库和每个关键字可以具有源路径(source属性)和行号(lineno属性)。源路径相对于生成规范文件的目录,因此如果移动规范,则不会引用正确的文件。如果源路径与库中的源路径相同,则省略关键字;如果由于某种原因从库中获取源路径和行号失败,则省略源路径和行号。

Libdoc automatically uses the XML format if the output file extension is *.xml or *.libspec. When using the special *.libspec extension, Libdoc automatically enables the options -f XML -s HTML which means creating an XML output file where keyword documentation is converted to HTML. If needed, the format can be explicitly set with the --format option.
如果输出文件扩展名为*.xml*.libspec,Libdoc将自动使用XML格式。当使用特殊的 *.libspec扩展名时,Libdoc会自动启用选项-f XML -s HTML,这意味着创建一个XML输出文件,其中关键字文档被转换为HTML。如果需要,可以使用--format选项显式设置格式。

libdoc OperatingSystem OperatingSystem.xml
libdoc test/resource.robot doc/resource.libspec
libdoc --format xml MyLibrary MyLibrary.spec
libdoc --format xml -s html MyLibrary MyLibrary.xml

The exact Libdoc spec file format is documented with an XML schema (XSD) at https://github.com/robotframework/robotframework/tree/master/doc/schema. The spec file format may change between Robot Framework major releases.
https://github.com/robotframework/robotframework/tree/master/doc/schema上,使用XML模式(XSD)记录了确切的Libdoc规范文件格式。规范文件格式可能会在Robot Framework主要版本之间发生变化。

To make it easier for external tools to know how to parse a certain spec file, the spec file root element has a dedicated specversion attribute. It was added in Robot Framework 3.2 with value 2 and earlier spec files can be considered to have version 1. The spec version will be incremented in the future if and when changes are made. Robot Framework 4.0 introduced new spec version 3 which is incompatible with earlier versions.
为了使外部工具更容易知道如何解析特定的spec文件,spec文件根元素有一个专用的specversion属性。它是在Robot Framework 3.2中添加的,值为2,早期的spec文件可以被认为是版本1。如果将来进行更改,等级库版本将递增。Robot Framework 4.0引入了新的规范版本3,该版本与早期版本不兼容。

Note 注意

The XML:HTML format introduced in Robot Framework 3.2. has been replaced by the format LIBSPEC ot the option combination --format XML --specdocformat HTML.
XML:HTML格式在Robot Framework 3.2中引入。已被格式LIBSPEC或选项组合--format XML --specdocformat HTML所取代。

Note 注意

Including source information and spec version are new in Robot Framework 3.2.
包括源信息和规范版本是Robot Framework 3.2中的新内容。

Libdoc JSON spec files Libdoc JSON规范文件

Since Robot Framework 4.0 Libdoc can also generate documentation in JSON format that is suitable for external tools such as editors or web pages. It contains all the same information as the HTML format but in a machine readable format.
自Robot Framework 4.0以来,Libdoc还可以生成JSON格式的文档,适用于编辑器或网页等外部工具。它包含与HTML格式相同的所有信息,但采用机器可读格式。

Similar to XML spec files the JSON spec files contain all information and can also be used as input to Libdoc. From that format any other output format can be created. By default the library documentation strings are converted to HTML format within the JSON output file.
与XML规范文件类似,JSON规范文件包含所有信息,也可以用作Libdoc的输入。从该格式可以创建任何其他输出格式。默认情况下,库文档字符串在JSON输出文件中转换为HTML格式。

The exact JSON spec file format is documented with an JSON schema at https://github.com/robotframework/robotframework/tree/master/doc/schema. The spec file format may change between Robot Framework major releases.
确切的JSON规范文件格式与JSON模式一起记录在https://github.com/robotframework/robotframework/tree/master/doc/schema上。规范文件格式可能会在Robot Framework主要版本之间发生变化。

Viewing information on console
在控制台上查看信息

Libdoc has three special commands to show information on the console. These commands are used instead of the name of the output file, and they can also take additional arguments.
LibDoc有三个特殊命令可以在控制台上显示信息。这些命令用于代替输出文件的名称,它们还可以接受其他参数。

list
List names of the keywords the library/resource contains. Can be limited to show only certain keywords by passing optional patterns as arguments. Keyword is listed if its name contains given pattern.
列出库/资源包含的关键字名称。通过传递可选模式作为参数,可以限制为仅显示某些关键字。如果关键字的名称包含给定的模式,则列出关键字。
show
Show library/resource documentation. Can be limited to show only certain keywords by passing names as arguments. Keyword is shown if its name matches any given name. Special argument intro will show only the library introduction and importing sections.
显示库/资源文档。通过将名称作为参数传递,可以限制为仅显示某些关键字。如果关键字的名称与任何给定的名称匹配,则会显示该关键字。特殊参数介绍将只显示库介绍和导入部分。
version
Show library version 显示库版本

Optional patterns given to list and show are case and space insensitive. Both also accept * and ? as wildcards.
listshow的可选模式不区分大小写和空格。两者都接受 *作为通配符。

Examples: 示例如下:

libdoc Dialogs list
libdoc SeleniumLibrary list browser
libdoc Remote::10.0.0.42:8270 show
libdoc Dialogs show PauseExecution execute*
libdoc SeleniumLibrary show intro
libdoc SeleniumLibrary version

5.1.2   Writing documentation
5.1.2编写文档

This section discusses writing documentation for Python based test libraries that use the static library API as well as for dynamic libraries and resource files. Creating test libraries and resource files is described in more details elsewhere in the User Guide.
本节讨论为使用静态库API的基于Python的测试库以及动态库资源文件编写文档。创建测试库资源文件的更多细节在《用户指南》中的其他地方进行了描述。

Python libraries Python库

The documentation for Python libraries that use the static library API is written simply as doc strings for the library class or module and for methods implementing keywords. The first line of the method documentation is considered as a short documentation for the keyword (used, for example, as a tool tip in links in the generated HTML documentation), and it should thus be as describing as possible, but not too long.
使用静态库API的Python库的文档被简单地编写为库类或模块以及实现关键字的方法的文档字符串。方法文档的第一行被认为是关键字的简短文档(例如,在生成的HTML文档中用作链接中的工具提示),因此它应该尽可能描述,但不要太长。

The simple example below illustrates how to write the documentation in general. How the HTML documentation generated based on this example looks like can be seen above, and there is also a bit longer example at the end of this chapter.
下面的简单示例说明了如何编写一般的文档。基于这个例子生成的HTML文档的样子可以在上面看到,在本章的最后还有一个更长的例子

class ExampleLibrary:
    """Library for demo purposes.

    This library is only used in an example and it doesn't do anything useful.
    """

    def my_keyword(self):
        """Does nothing."""
        pass

    def your_keyword(self, arg):
        """Takes one argument and *does nothing* with it.

        Examples:
        | Your Keyword | xxx |
        | Your Keyword | yyy |
        """
        pass

Tip 尖端

If you library does some initialization work that should not be done when using Libdoc, you can easily detect is Robot Framework running
如果你的库做了一些在使用Libdoc时不应该做的初始化工作,你可以很容易地检测到Robot Framework正在运行。

Tip 尖端

For more information on Python documentation strings, see PEP-257.
有关Python文档字符串的更多信息,请参见PEP-257

Dynamic libraries 动态库

To be able to generate meaningful documentation for dynamic libraries, the libraries must return keyword argument names and documentation using get_keyword_arguments and get_keyword_documentation methods (or using their camelCase variants getKeywordArguments and getKeywordDocumentation). Libraries can also support general library documentation via special __intro__ and __init__ values to the get_keyword_documentation method.
为了能够为动态库生成有意义的文档,库必须使用get_keyword_argumentsget_keyword_documentation方法(或使用其camelCase变体getKeywordArgumentsgetKeywordDocumentation)返回关键字参数名称和文档。库还可以通过get_keyword_documentation方法的特殊__intro____init__值来支持常规库文档。

See the Dynamic library API section for more information about how to create these methods.
有关如何创建这些方法的详细信息,请参阅动态库API部分。

Importing section 横截面

A separate section about how the library is imported is created based on its initialization methods. If the library has an __init__ method that takes arguments in addition to self, its documentation and arguments are shown.
根据库的初始化方法创建了一个单独的部分,介绍如何导入库。如果库有一个__init__方法,除了self之外还接受参数,则会显示其文档和参数。

class TestLibrary:

    def __init__(self, mode='default')
        """Creates new TestLibrary. `mode` argument is used to determine mode."""
        self.mode = mode

    def some_keyword(self, arg):
        """Does something based on given `arg`.

        What is done depends on the `mode` specified when `importing` the library.
        """
        if self.mode == 'secret':
             # ...

Resource file documentation
资源文件文档

Keywords in resource files can have documentation using [Documentation] setting, and this documentation is also used by Libdoc. First line of the documentation (until the first implicit newline or explicit \n) is considered to be the short documentation similarly as with test libraries.
资源文件中的关键字可以有使用[文档]设置的文档,Libdoc也使用此文档。文档的第一行(直到第一个隐式换行符或显式\n)被认为是短文档,与测试库类似。

Also the resource file itself can have Documentation in the Setting section for documenting the whole resource file.
资源文件本身也可以在设置部分中包含文档,用于记录整个资源文件。

Possible variables in resource files can not be documented.
无法记录资源文件中可能的变量。

*** Settings ***
Documentation    Resource file for demo purposes.
...              This resource is only used in an example and it doesn't do anything useful.

*** Keywords ***
My Keyword
    [Documentation]   Does nothing
    No Operation

Your Keyword
    [Arguments]  ${arg}
    [Documentation]   Takes one argument and *does nothing* with it.
    ...
    ...    Examples:
    ...    | Your Keyword | xxx |
    ...    | Your Keyword | yyy |
    No Operation

5.1.3   Documentation syntax
5.1.3文档语法

Libdoc supports documentation in Robot Framework's own documentation syntax, HTML, plain text, and reStructuredText. The format to use can be specified in library source code using ROBOT_LIBRARY_DOC_FORMAT attribute or given from the command line using --docformat (-F) option. In both cases the possible case-insensitive values are ROBOT (default), HTML, TEXT and reST.
Libdoc支持Robot Framework自己的文档语法,HTML,纯文本和reStructuredText。要使用的格式可以在库源代码中使用ROBOT_LIBRARY_DOC_FORMAT属性指定,也可以在命令行中使用--docformat(-F)选项指定。在这两种情况下,可能的大小写不敏感值是ROBOT(默认),HTMLTEXTreST

Robot Framework's own documentation format is the default and generally recommended format. Other formats are especially useful when using existing code with existing documentation in test libraries.
Robot框架自己的文档格式是默认且通常推荐的格式。当将现有代码与测试库中的现有文档一起使用时,其他格式特别有用。

Robot Framework documentation syntax
Robot Framework文档语法

Most important features in Robot Framework's documentation syntax are formatting using *bold* and _italic_, custom links and automatic conversion of URLs to links, and the possibility to create tables and pre-formatted text blocks (useful for examples) simply with pipe character. If documentation gets longer, support for section titles can also be handy.
Robot框架文档语法中最重要的功能是使用*bold*_italic_进行格式设置、自定义链接和URL自动转换为链接,以及简单地使用管道字符创建表格和预格式文本块(对于示例很有用)的可能性。如果文档变得更长,对节标题的支持也很方便。

Some of the most important formatting features are illustrated in the example below. Notice that since this is the default format, there is no need to use ROBOT_LIBRARY_DOC_FORMAT attribute nor give the format from the command line.
下面的示例说明了一些最重要的格式设置功能。请注意,由于这是默认格式,因此不需要使用ROBOT_LIBRARY_DOC_FORMAT属性,也不需要从命令行指定格式。

"""Example library in Robot Framework format.

- Formatting with *bold* and _italic_.
- URLs like http://example.com are turned to links.
- Custom links like [http://robotframework.org|Robot Framework] are supported.
- Linking to `My Keyword` works.
"""

def my_keyword():
    """Nothing more to see here."""
Creating table of contents automatically
自动创建目录

With bigger libraries it is often useful to add a table of contents to the library introduction. When using the Robot Framework documentation format, this can be done automatically by adding a special %TOC% marker into a line on its own. The table of contents is created based on the top-level section titles (e.g. = Section =) used in the introduction. In addition to them, the TOC also gets links to the automatically created sections for shortcuts and keywords as well as for importing and tags sections when applicable.
对于较大的库,在库介绍中添加目录通常很有用。当使用Robot Framework文档格式时,这可以通过将特殊的%TOC%标记添加到单独的行中来自动完成。目录是根据介绍中使用的顶级章节标题(例如= Section =)创建的。除此之外,TOC还可以获得自动创建的快捷方式和关键字部分的链接,以及导入和标记部分(如果适用)的链接。

"""Example library demonstrating TOC generation.

The %TOC% marker only creates the actual table of contents and possible
header or other explanation needs to be added separately like done below.

== Table of contents ==

%TOC%

= Section title =

The top-level section titles are automatically added to the TOC.

= Second section =

== Sub section ==

Sub section titles are not added to the TOC.
"""

def my_keyword():
    """Nothing more to see here."""

Note 注意

Automatic TOC generation is a new feature in Robot Framework 3.2.
自动TOC生成是Robot Framework 3.2中的一项新功能。

HTML documentation syntax
HTML文档语法

When using HTML format, you can create documentation pretty much freely using any syntax. The main drawback is that HTML markup is not that human friendly, and that can make the documentation in the source code hard to maintain and read. Documentation in HTML format is used by Libdoc directly without any transformation or escaping. The special syntax for linking to keywords using syntax like `My Keyword` is supported, however.
当使用HTML格式时,您可以使用任何语法非常自由地创建文档。主要的缺点是HTML标记不是那么人性化,这会使源代码中的文档难以维护和阅读。Libdoc直接使用HTML格式的文档,无需任何转换或转义。但是,支持使用`My Keyword`等语法链接到关键字的特殊语法。

Example below contains the same formatting examples as the previous example. Now ROBOT_LIBRARY_DOC_FORMAT attribute must be used or format given on the command line like --docformat HTML.
下面的示例包含与上一个示例相同的格式示例。现在必须使用ROBOT_LIBRARY_DOC_FORMAT属性或在命令行上指定格式,如--docformat HTML

"""Example library in HTML format.

<ul>
  <li>Formatting with <b>bold</b> and <i>italic</i>.
  <li>URLs are not turned to links automatically.
  <li>Custom links like <a href="http://www.w3.org/html">HTML</a> are supported.
  <li>Linking to `My Keyword` works.
</ul>
"""
ROBOT_LIBRARY_DOC_FORMAT = 'HTML'

def my_keyword():
    """Nothing more to see here."""

Plain text documentation syntax
纯文本文档语法

When the plain text format is used, Libdoc uses the documentation as-is. Newlines and other whitespace are preserved except for indentation, and HTML special characters (<>&) escaped. The only formatting done is turning URLs into clickable links and supporting internal linking like `My Keyword`.
当使用纯文本格式时,Libdoc按原样使用文档。除了缩进和HTML特殊字符(<>&)外,保留换行符和其他空白。唯一做的格式化是把网址变成可点击的链接,并支持内部链接,如'我的关键字'

"""Example library in plain text format.

- Formatting is not supported.
- URLs like http://example.com are turned to links.
- Custom links are not supported.
- Linking to `My Keyword` works.
"""
ROBOT_LIBRARY_DOC_FORMAT = 'text'

def my_keyword():
    """Nothing more to see here."""

reStructuredText documentation syntax
reStructuredText文档语法

reStructuredText is simple yet powerful markup syntax used widely in Python projects (including this User Guide) and elsewhere. The main limitation is that you need to have the docutils module installed to be able to generate documentation using it. Because backtick characters have special meaning in reStructuredText, linking to keywords requires them to be escaped like \`My Keyword\`.
reStructuredText是一种简单而强大的标记语法,广泛用于Python项目(包括本用户指南)和其他地方。主要的限制是你需要安装docutils模块才能使用它生成文档。因为反勾字符在reStructuredText中有特殊的含义,链接到关键字需要像\`My Keyword\`一样转义它们。

One of the nice features that reStructured supports is the ability to mark code blocks that can be syntax highlighted. Syntax highlight requires additional Pygments module and supports all the languages that Pygments supports.
reStructured支持的一个很好的特性是能够标记可以语法突出显示的代码块。高亮显示需要额外的Pygments模块,并支持Pygments支持的所有语言。

"""Example library in reStructuredText format.

- Formatting with **bold** and *italic*.
- URLs like http://example.com are turned to links.
- Custom links like reStructuredText__ are supported.
- Linking to \`My Keyword\` works but requires backtics to be escaped.

__ http://docutils.sourceforge.net

.. code:: robotframework

    *** Test Cases ***
    Example
        My keyword    # How cool is this!!?!!?!1!!
"""
ROBOT_LIBRARY_DOC_FORMAT = 'reST'

def my_keyword():
    """Nothing more to see here."""

5.1.4   Internal linking 5.1.4内部链接

Libdoc supports internal linking to keywords and different sections in the documentation. Linking is done by surrounding the target name with backtick characters like `target`. Target names are case-insensitive and possible targets are explained in the subsequent sections.
Libdoc支持文档中关键字和不同部分的内部链接。链接是通过在目标名称周围使用反勾字符(如`target`)来完成的。目标名称不区分大小写,可能的目标将在后续部分中进行说明。

There is no error or warning if a link target is not found, but instead Libdoc just formats the text in italics. Earlier this formatting was recommended to be used when referring to keyword arguments, but that was problematic because it could accidentally create internal links. Nowadays it is recommended to use inline code style with double backticks like ``argument`` instead. The old formatting of single backticks may even be removed in the future in favor of giving an error when a link target is not found.
如果没有找到链接目标,不会出现错误或警告,但Libdoc只是将文本格式化为斜体。以前,当引用关键字参数时,建议使用这种格式,但这是有问题的,因为它可能会意外地创建内部链接。现在建议使用带双反引号的内联代码样式,``argument``。旧的单反引号格式甚至可能在未来被删除,以便在找不到链接目标时给出错误。

In addition to the examples in the following sections, internal linking and argument formatting is shown also in the longer example at the end of this chapter.
除了下面几节中的例子外,本章末尾的较长例子中也展示了内部链接和参数格式。

Linking to keywords 链接到关键字

All keywords the library have automatically create link targets and they can be linked using syntax `Keyword Name`. This is illustrated with the example below where both keywords have links to each others.
库中的所有关键字都会自动创建链接目标,并且可以使用语法`Keyword Name`进行链接。下面的例子说明了这一点,其中两个关键字都有彼此的链接。

def keyword(log_level="INFO"):
    """Does something and logs the output using the given level.

    Valid values for log level` are "INFO" (default) "DEBUG" and "TRACE".

    See also `Another Keyword`.
    """
    # ...

def another_keyword(argument, log_level="INFO"):
    """Does something with the given argument else and logs the output.

    See `Keyword` for information about valid log levels.
    """
    # ...

Note 注意

When using reStructuredText documentation syntax, backticks must be escaped like \`Keyword Name\`.
当使用reStructuredText文档语法时,反引号必须像\`Keyword Name\`一样转义。

Linking to automatic sections
链接到自动节

The documentation generated by Libdoc always contains sections for overall library introduction and for keywords. If a library itself takes arguments, there is also separate importing section. If any of the keywords has tags, a separate selector for them is also shown in the overview.
Libdoc生成的文档总是包含整个库介绍和关键字部分。如果一个库本身接受参数,那么也有单独的导入部分。如果任何关键字具有标签,则概述中还会显示它们的单独选择器。

All the sections act as targets that can be linked, and the possible target names are listed in the table below. Using these targets is shown in the example of the next section.
所有部分都充当可以链接的目标,下表列出了可能的目标名称。使用这些目标将在下一节的示例中展示。

Automatic section link targets
自动分段链接目标
Section 部分 Target 目标
Introduction 介绍 `introduction` and `library introduction`
“Introduction”“Library Introduction”
Importing 进口 `importing` and `library importing`
“导入”“库导入”
Keywords 关键词 `keywords` `关键字`

Note 注意

Before Robot Framework 4.0 there were also sections for tags and shortcuts. In Robot Framework 4.0 these have been removed in favor of the overview menu. This means that prior linking to shortcuts or tags sections does not work.
在Robot Framework 4.0之前,也有标签和快捷方式的部分。在Robot Framework 4.0中,这些已被删除,以支持概览菜单。这意味着之前链接到快捷方式或标签部分不起作用。

Linking to custom sections
链接到自定义节

Robot Framework's documentation syntax supports custom section titles, and the titles used in the library or resource file introduction automatically create link targets. The example below illustrates linking both to automatic and custom sections:
Robot Framework的文档语法支持自定义节标题,并且库或资源文件介绍中使用的标题会自动创建链接目标。下面的示例说明了如何链接到自动节和自定义节:

"""Library for Libdoc demonstration purposes.

This library does not do anything useful.

= My section  =

We do have a custom section in the documentation, though.
"""

def keyword():
    """Does nothing.

    See `introduction` for more information and `My section` to test how
    linking to custom sections works.
    """
    pass

Note 注意

Linking to custom sections works only when using Robot Framework documentation syntax.
仅当使用Robot Framework文档语法时,链接到自定义节才有效。

5.1.5   Representing arguments
5.1.5表示论点

Libdoc shows information about keywords' arguments automatically.
Libdoc自动显示关键字参数的信息。

Included information 包括信息

The following information is shown for all keywords regardless are they implemented in libraries or in resource files:
显示所有关键字的以下信息,无论它们是在库中还是在资源文件中实现的:

  • Argument name. User keyword arguments are shown without the ${} decoration to make arguments look the same regardless where keywords originate from.
    参数名称。用户关键字参数显示时没有${}装饰,以使参数看起来相同,而不管关键字来自何处。
  • Marker telling is the argument positional-only, named-only, free positional, free named, or normal argument that can be given either by position or by name.
    标记告诉是参数仅位置仅命名自由位置自由命名正常参数,可以通过位置或名称给出。
  • Possible default value. Shown like = 42.
    可能的默认值。显示为= 42
  • Possible type. Shown like <int>. Can be a link to type documentation as explained in the next section.
    可能的类型。显示为<int>。可以是到类型文档的链接,如下一节所述。

When referring to arguments in keyword documentation, it is recommended to use inline code style like ``argument``.
在关键字文档中引用参数时,建议使用内联代码样式,如``argument``

Automatically listing type documentation
自动列出类型文档

As mentioned above, Libdoc automatically shows possible type information when listing arguments. If the type is a custom type based on Enum or TypedDict, the type is automatically converted, or the type has custom converter, also the type itself is listed separately to show more information about it. When these types are used in arguments, the type name also becomes a link to the type information.
如上所述,Libdoc在列出参数时会自动显示可能的类型信息。如果类型是基于EnumTypedDict的自定义类型,则类型会自动转换,或者类型具有自定义转换器,并且类型本身也会单独列出以显示有关它的更多信息。当这些类型在参数中使用时,类型名称也会成为指向类型信息的链接。

All listed data types show possible type documentation as well as what argument types are supported. In addition to that, types based on Enum list available members and types based on TypedDict show the dictionary structure.
所有列出的数据类型都显示了可能的类型文档以及支持的参数类型。除此之外,基于Enum的类型列出可用成员,基于TypedDict的类型显示字典结构。

Note 注意

Automatically listing types based on Enum and TypedDict is new in Robot Framework 4.0. Listing other types is new in Robot Framework 5.0.
自动列出基于EnumTypedDict的类型是Robot Framework 4.0中的新功能。列出其他类型是Robot Framework 5.0中的新功能。

5.1.6   Libdoc example 5.1.6 Libdoc示例

The following example illustrates how to use the most important documentation formatting possibilities, internal linking, and so on. Click here to see how the generated documentation looks like.
下面的示例说明了如何使用最重要的文档格式设置、内部链接等。单击此处查看生成的文档的外观。

class LoggingLibrary:
    """Library for logging messages.

    = Table of contents =

    %TOC%

    = Usage =

    This library has several keyword, for example `Log Message`, for logging
    messages. In reality the library is used only for _Libdoc_ demonstration
    purposes.

    = Valid log levels =

    Valid log levels are ``INFO``, ``DEBUG``, and ``TRACE``. The default log
    level can be set during `importing`.

    = Examples =

    Notice how keywords are linked from examples.

    | `Log Message`      | My message    |                |               |
    | `Log Two Messages` | My message    | Second message | level=DEBUG   |
    | `Log Messages`     | First message | Second message | Third message |
    """
    ROBOT_LIBRARY_VERSION = '0.1'

    def __init__(self, default_level='INFO'):
        """The default log level can be given at library import time.

        See `Valid log levels` section for information about available log
        levels.

        Examples:

        | =Setting= |     =Value=    | =Value= |          =Comment=         |
        | Library   | LoggingLibrary |         | # Use default level (INFO) |
        | Library   | LoggingLibrary | DEBUG   | # Use the given level      |
        """
        self.default_level = self._verify_level(default_level)

    def _verify_level(self, level):
        level = level.upper()
        if level not in ['INFO', 'DEBUG', 'TRACE']:
            raise RuntimeError("Invalid log level'%s'. Valid levels are "
                               "'INFO', 'DEBUG', and 'TRACE'")
        return level

    def log_message(self, message, level=None):
        """Writes given message to the log file using the specified log level.

        The message to log and the log level to use are defined using
        ``message`` and ``level`` arguments, respectively.

        If no log level is given, the default level given during `library
        importing` is used.
        """
        level = self._verify_level(level) if level else self.default_level
        print("*%s* %s" % (level, message))

    def log_two_messages(self, message1, message2, level=None):
        """Writes given messages to the log file using the specified log level.

        See `Log Message` keyword for more information.
        """
        self.log_message(message1, level)
        self.log_message(message2, level)

    def log_messages(self, *messages):
        """Logs given messages using the log level set during `importing`.

        See also `Log Message` and `Log Two Messages`.
        """
        for msg in messages:
            self.log_message(msg)

All standard libraries have documentation generated by Libdoc and their documentation (and source code) act as a more realistic examples.
所有标准库都有LibDoc生成的文档,它们的文档(和源代码)充当更现实的示例。

5.2   Test data documentation tool (Testdoc)
5.2测试数据文档工具(Testdoc)

Testdoc is Robot Framework's built-in tool for generating high level documentation based on test cases. The created documentation is in HTML format and it includes name, documentation and other metadata of each test suite and test case, as well as the top-level keywords and their arguments.
Testdoc是Robot Framework的内置工具,用于基于测试用例生成高级文档。创建的文档是HTML格式的,它包括每个测试套件和测试用例的名称、文档和其他元数据,以及顶级关键字及其参数。

5.2.1   General usage 5.2.1一般用法

Synopsis 概要

python -m robot.testdoc [options] data_sources output_file

Options 选项

-T, --title <title>
 Set the title of the generated documentation. Underscores in the title are converted to spaces. The default title is the name of the top level suite.
设置生成文档的标题。标题中的下划线将转换为空格。默认标题是顶级套件的名称。
-N, --name <name>
 Override the name of the top level test suite.
指定顶级测试套件的名称。
-D, --doc <doc>
 Override the documentation of the top level test suite.
检查顶级测试套件的文档。
-M, --metadata <name:value>
 Set/override free metadata of the top level test suite.
设置/覆盖顶级测试套件的自由元数据。
-G, --settag <tag>
 Set given tag(s) to all test cases.
为所有测试用例设置给定标签。
-t, --test <name>
 Include tests by name. 按名称包括测试。
-s, --suite <name>
 Include suites by name. 按名称包括套房。
-i, --include <tag>
 Include tests by tags. 按标签包括测试。
-e, --exclude <tag>
 Exclude tests by tags. 标签测试。
-A, --argumentfile <path>
 Text file to read more arguments from. Works exactly like argument files when running tests.
要从中读取更多参数的文本文件。运行测试时,其工作方式与参数文件完全相同。
-h, --help Print this help in the console.
在控制台中打印此帮助。

All options except --title have exactly the same semantics as same options have when executing test cases.
除了--title之外的所有选项都与执行测试用例时的相同选项具有完全相同的语义。

5.2.2   Generating documentation
5.2.2生成文档

Data can be given as a single file, directory, or as multiple files and directories. In all these cases, the last argument must be the file where to write the output.
数据可以作为单个文件、目录或多个文件和目录提供。在所有这些情况下,最后一个参数必须是写入输出的文件。

Testdoc can be executed as an installed module like python -m robot.testdoc or as a script like python path/robot/testdoc.py.
Testdoc可以作为一个安装好的模块来执行,比如python-mrobot.testdoc,或者作为一个脚本来执行,比如pythonpath/robot/testdoc.py

Examples: 示例如下:

python -m robot.testdoc my_test.robot testdoc.html
python path/to/robot/testdoc.py --name "Smoke tests" --include smoke path/to/tests smoke.html

5.3   Test data clean-up tool (Tidy)
5.3测试数据清理工具(Tidy)

The built-in Tidy tool was deprecated in Robot Framework 4.1 in favor of the new and enhanced external Robotidy tool. It was removed altogether in Robot Framework 5.0.
内置的Tidy工具在Robot Framework 4.1中被弃用,取而代之的是新的增强的外部Robotidy工具。它在Robot Framework 5.0中被完全删除。

5.4   External tools 5.4外部工具

There are plenty of external tools that can be used with Robot Framework. These tools include plugins for various IDEs and text editors, tools for parallel execution and data-driven testing, plugins for continuous integration systems, and so on.
有很多外部工具可以与Robot Framework一起使用。这些工具包括用于各种IDE和文本编辑器的插件、用于并行执行和数据驱动测试的工具、用于持续集成系统的插件等等。

These tools are developed as separate projects independently from Robot Framework itself. For a list of the available tools see http://robotframework.org/.
这些工具是作为独立于Robot Framework本身的单独项目开发的。有关可用工具的列表,请参见http://robotframework.org/

6   Appendices 6附录

6.1   Available settings 6.1可用设置

This appendix lists all settings that can be used in different sections.
本附录列出了可在不同部分中使用的所有设置。

Note 注意

Settings can be localized. See the Translations appendix for supported translations.
设置可以本地化。有关支持的翻译,请参见翻译附录。

6.1.1   Setting section 6.1.1整定段

The Setting section is used to import libraries, resource files and variable files and to define metadata for test suites and test cases. It can be included in test case files and resource files. Note that in a resource file, a Setting section can only include settings for importing libraries, resources, and variables.
设置部分用于导入库、资源文件和变量文件,并定义测试套件和测试用例的元数据。它可以包含在测试用例文件和资源文件中。请注意,在资源文件中,设置节只能包含用于导入库、资源和变量的设置。

Settings available in the Setting section
设置部分中的可用设置
Name 名称 Description 描述
Library 图书馆 Used for importing libraries.
用于导入库
Resource 资源 Used for taking resource files into use.
用于使用资源文件
Variables 变量 Used for taking variable files into use.
用于使用变量文件
Name 名称 Used for setting a custom suite name.
用于设置自定义套件名称
Documentation 文件 Used for specifying a suite or resource file documentation.
用于指定套件资源文件文档。
Metadata 元数据 Used for setting free suite metadata.
用于设置自由套件元数据
Suite Setup 套件安装程序 Used for specifying the suite setup.
用于指定套件设置
Suite Teardown Teardown套房 Used for specifying the suite teardown.
用于指定套件拆卸
Test Tags 测试标签 Used for specifying test case tags for all tests in a suite.
用于为套件中的所有测试指定测试用例标记
Force Tags, Default Tags 强制标签、默认标签 Deprecated settings for specifying test case tags.
不推荐用于指定测试用例标记的设置。
Keyword Tags 关键字标签 Used for specifying user keyword tags for all keywords in a certain file.
用于为某个文件中的所有关键字指定用户关键字标签
Test Setup 测试设置。 Used for specifying a default test setup.
用于指定默认测试设置
Test Teardown 撕裂测试仪 Used for specifying a default test teardown.
用于指定默认测试拆卸
Test Template 测试模板 Used for specifying a default template keyword for test cases.
用于指定测试用例的默认模板关键字
Test Timeout 测试超时 Used for specifying a default test case timeout.
用于指定默认测试用例超时
Task Setup, Task Teardown, Task Template, Task Timeout
任务设置、任务分解、任务模板、任务分解
Aliases for Test Setup, Test Teardown, Test Template and Test Timeout, respectively, that can be used when creating tasks.
分别用于测试设置、测试拆卸、测试模板和测试模板的别名,可在创建任务时使用。

6.1.2   Test Case section 6.1.2测试用例部分

The settings in the Test Case section are always specific to the test case for which they are defined. Some of these settings override the default values defined in the Settings section.
“测试用例”部分中的设置始终特定于为其定义的测试用例。其中某些设置会覆盖“设置”部分中定义的默认值。

Exactly same settings are available when creating tasks in the Task section.
在“任务”部分中创建任务时,可以使用完全相同的设置。

Settings available in the Test Case section
测试用例部分中的可用设置
Name 名称 Description 描述
[Documentation] [文件] Used for specifying a test case documentation.
用于指定测试用例文档
[Tags] [标签] Used for tagging test cases.
用于标记测试用例
[Setup] [设置] Used for specifying a test setup.
用于指定测试设置
[Teardown] [拆除] Used for specifying a test teardown.
用于指定测试拆卸
[Template] [模板] Used for specifying a template keyword.
用于指定模板关键字
[Timeout] [超时] Used for specifying a test case timeout.
用于指定测试用例超时

6.1.3   Keyword section 6.1.3关键字部分

Settings in the Keyword section are specific to the user keyword for which they are defined.
“关键字”部分中的设置特定于为其定义这些设置的用户关键字。

Settings available in the Keyword section
关键字部分中可用的设置
Name 名称 Description 描述
[Documentation] [文件] Used for specifying a user keyword documentation.
用于指定用户关键字文档
[Tags] [标签] Used for specifying user keyword tags.
用于指定用户关键字标记
[Arguments] [争论] Used for specifying user keyword arguments.
用于指定用户关键字参数
[Setup] [设置] Used for specifying a user keyword setup. New in Robot Framework 7.0.
用于指定用户关键字设置。机器人框架7.0中的新功能。
[Teardown] [拆除] Used for specifying user keyword teardown.
用于指定用户关键字teardown
[Timeout] [超时] Used for specifying a user keyword timeout.
用于指定用户关键字超时
[Return] [返回] Used for specifying user keyword return values. Deprecated in Robot Framework 7.0. Use the RETURN statement instead.
用于指定用户关键字返回值。在Robot Framework 7.0中弃用。请改用RETURN语句。

6.2   Command line options 6.2命令行选项

This appendix lists all the command line options that are available when executing test cases and when post-processing outputs. Also environment variables affecting execution and post-processing are listed.
本附录列出了执行测试用例后处理输出时可用的所有命令行选项。还列出了影响执行和后处理的环境变量。

6.2.1   Command line options for test execution
6.2.1测试执行的命令行选项

--rpa Turn on generic automation mode.
打开通用自动化模式。
--language <lang>
 Activate localization. lang can be a name or a code of a built-in language, or a path or a module name of a custom language file.
启动定位lang可以是内置语言的名称或代码,也可以是自定义语言文件的路径或模块名称。
-F, --extension <value>
 Parse only these files when executing a directory.
执行目录时只解析这些文件
-I, --parseinclude <pattern>
 Parse only matching files when executing a directory.
执行目录时只解析匹配的文件
-N, --name <name>
 Sets the name of the top-level test suite.
设置顶级测试套件的名称。
-D, --doc <document>
 Sets the documentation of the top-level test suite.
设置顶级测试套件的文档。
-M, --metadata <name:value>
 Sets free metadata for the top level test suite.
为顶级测试套件设置可用元数据
-G, --settag <tag>
 Sets the tag(s) to all executed test cases.
为所有已执行的测试用例设置标记
-t, --test <name>
 Selects the test cases by name.
按名称命名测试用例
--task <name> Alias for --test that can be used when executing tasks.
执行任务时可以使用的测试
-s, --suite <name>
 Selects the test suites by name.
按名称命名测试套件
-R, --rerunfailed <file>
 Selects failed tests from an earlier output file to be re-executed.
重新执行早期输出文件中失败的测试。
-S, --rerunfailedsuites <file>
 Selects failed test suites from an earlier output file to be re-executed.
从要重新执行的早期输出文件删除失败的测试套件
-i, --include <tag>
 Selects the test cases by tag.
按标签搜索测试用例
-e, --exclude <tag>
 Selects the test cases by tag.
按标签搜索测试用例
--skip <tag> Tests having given tag will be skipped. Tag can be a pattern.
跳过具有给定标签的测试。标签可以是一种模式。
--skiponfailure <tag>
 Tests having given tag will be skipped if they fail.
如果测试失败,将跳过具有给定标签的测试。
-v, --variable <name:value>
 Sets individual variables.
设置单个变量
-V, --variablefile <path:args>
 Sets variables using variable files.
使用变量文件设置变量。
-d, --outputdir <dir>
 Defines where to create output files.
定义在何处创建输出文件
-o, --output <file>
 Sets the path to the generated output file.
设置生成的输出文件的路径。
--legacyoutput Creates output file in Robot Framework 6.x compatible format.
Robot Framework 6.x兼容格式创建输出文件。
-l, --log <file>
 Sets the path to the generated log file.
设置生成的日志文件的路径。
-r, --report <file>
 Sets the path to the generated report file.
设置生成的报告文件的路径。
-x, --xunit <file>
 Sets the path to the generated xUnit compatible result file.
设置生成的xUnit兼容结果文件的路径。
-b, --debugfile <file>
 A debug file that is written during execution.
在执行期间写入的调试文件
-T, --timestampoutputs
 Adds a timestamp to output files listed above.
将时间戳添加到上面列出的输出文件
--splitlog Split log file into smaller pieces that open in browser transparently.
将日志文件拆分为在浏览器中透明打开的较小部分。
--logtitle <title>
 Sets a title for the generated test log.
为生成的测试日志设置标题
--reporttitle <title>
 Sets a title for the generated test report.
为生成的测试报告设置标题
--reportbackground <colors>
 Sets background colors of the generated report.
设置生成的报告的背景颜色。
--maxerrorlines <lines>
 Sets the number of error lines shown in report when tests fail.
设置测试失败时报告中显示的错误行数
--maxassignlength <characters>
 Sets the number of characters shown in log when variables are assigned.
设置变量赋值时日志中显示的字符数。
-L, --loglevel <level>
 Sets the threshold level for logging. Optionally the default visible log level can be given separated with a colon (:).
设置日志记录的阈值级别。默认可见日志级别可以用冒号(:)分隔。
--suitestatlevel <level>
 Defines how many levels to show in the Statistics by Suite table in outputs.
定义要在输出的“Statistics by Suite”表中显示的级别数。
--tagstatinclude <tag>
 Includes only these tags in the Statistics by Tag table.
在“按标签统计”表中仅包括这些标签
--tagstatexclude <tag>
 Excludes these tags from the Statistics by Tag table.
从“按标记统计”表中排除这些标记
--tagstatcombine <tags:title>
 Creates combined statistics based on tags.
基于标记创建组合统计信息。
--tagdoc <pattern:doc>
 Adds documentation to the specified tags.
将文档添加到指定的标记
--tagstatlink <pattern:link:title>
 Adds external links to the Statistics by Tag table.
外部链接添加到“按标记统计”表中。
--expandkeywords <name:pattern|tag:pattern>
 Automatically expand keywords in the generated log file.
在生成的日志文件中自动展开关键字
--removekeywords <all|passed|name:pattern|tag:pattern|for|while|wuks>
 Removes keyword data from the generated log file.
从生成的日志文件中删除关键字数据
--flattenkeywords <for|while|iteration|name:pattern|tag:pattern>
 Flattens keywords in the generated log file.
在生成的日志文件中展平关键字
--listener <name:args>
 Sets a listener for monitoring test execution.
设置用于监视测试执行的侦听器。
--nostatusrc Sets the return code to zero regardless of failures in test cases. Error codes are returned normally.
返回代码设置为零,而不管测试用例中是否失败。错误代码正常返回。
--runemptysuite
 Executes tests also if the selected test suites are empty.
如果选定的测试套件为空,也执行测试。
--dryrun In the dry run mode tests are run without executing keywords originating from test libraries. Useful for validating test data syntax.
空运行模式下,测试在不执行源自测试库的关键字的情况下运行。用于验证测试数据语法。
-X, --exitonfailure
 Stops test execution if any test fails.
如果任何测试失败,则停止测试执行
--exitonerror Stops test execution if any error occurs when parsing test data, importing libraries, and so on.
如果在分析测试数据、导入库等过程中发生任何错误,则停止测试执行
--skipteardownonexit
 Skips teardowns if test execution is prematurely stopped.
如果测试执行过早停止,则跳过拆卸
--prerunmodifier <name:args>
 Activate programmatic modification of test data.
激活测试数据的编程修改
--prerebotmodifier <name:args>
 Activate programmatic modification of results.
激活结果的程序化修改
--randomize <all|suites|tests|none>
 Randomizes test execution order.
随机化测试执行顺序。
--console <verbose|dotted|quiet|none>
 Console output type.
控制台输出类型
--dotted Shortcut for --console dotted.
--console dotted
--quiet Shortcut for --console quiet.
快捷方式--控制台安静
-W, --consolewidth <width>
 Sets the width of the console output.
设置控制台输出的宽度。
-C, --consolecolors <auto|on|ansi|off>
 Specifies are colors used on the console.
指定控制台上使用的颜色。
-K, --consolemarkers <auto|on|off>
 Show markers on the console when top level keywords in a test case end.
当测试用例中的顶级关键字结束时,在控制台上显示标记。
-P, --pythonpath <path>
 Additional locations to add to the module search path.
要添加到模块搜索路径的其他位置。
-A, --argumentfile <path>
 A text file to read more arguments from.
一个文本文件,用于读取更多参数
-h, --help Prints usage instructions.
打印使用说明
--version Prints the version information.
打印版本信息

6.2.2   Command line options for post-processing outputs
6.2.2后处理输出的命令行选项

--rpa Turn on generic automation mode.
打开通用自动化模式。
-R, --merge Changes result combining behavior to merging.
将结果组合行为更改为合并
-N, --name <name>
 Sets the name of the top level test suite.
设置顶级测试套件的名称。
-D, --doc <document>
 Sets the documentation of the top-level test suite.
设置顶级测试套件的文档。
-M, --metadata <name:value>
 Sets free metadata for the top-level test suite.
为顶级测试套件设置可用元数据
-G, --settag <tag>
 Sets the tag(s) to all processed test cases.
为所有已处理的测试用例设置标记
-t, --test <name>
 Selects the test cases by name.
按名称命名测试用例
--task <name> Alias for --test.
测试的...
-s, --suite <name>
 Selects the test suites by name.
按名称命名测试套件
-i, --include <tag>
 Selects the test cases by tag.
按标签搜索测试用例
-e, --exclude <tag>
 Selects the test cases by tag.
按标签搜索测试用例
-d, --outputdir <dir>
 Defines where to create output files.
定义在何处创建输出文件
-o, --output <file>
 Sets the path to the generated output file.
设置生成的输出文件的路径。
--legacyoutput Creates output file in Robot Framework 6.x compatible format.
Robot Framework 6.x兼容格式创建输出文件。
-l, --log <file>
 Sets the path to the generated log file.
设置生成的日志文件的路径。
-r, --report <file>
 Sets the path to the generated report file.
设置生成的报告文件的路径。
-x, --xunit <file>
 Sets the path to the generated xUnit compatible result file.
设置生成的xUnit兼容结果文件的路径。
-T, --timestampoutputs
 Adds a timestamp to output files listed above.
将时间戳添加到上面列出的输出文件
--splitlog Split log file into smaller pieces that open in browser transparently.
将日志文件拆分为在浏览器中透明打开的较小部分。
--logtitle <title>
 Sets a title for the generated test log.
为生成的测试日志设置标题
--reporttitle <title>
 Sets a title for the generated test report.
为生成的测试报告设置标题
--reportbackground <colors>
 Sets background colors of the generated report.
设置生成的报告的背景颜色。
-L, --loglevel <level>
 Sets the threshold level to select log messages. Optionally the default visible log level can be given separated with a colon (:).
设置选择日志消息的阈值级别。默认可见日志级别可以用冒号(:)分隔。
--suitestatlevel <level>
 Defines how many levels to show in the Statistics by Suite table in outputs.
定义要在输出的“Statistics by Suite”表中显示的级别数。
--tagstatinclude <tag>
 Includes only these tags in the Statistics by Tag table.
在“按标签统计”表中仅包括这些标签
--tagstatexclude <tag>
 Excludes these tags from the Statistics by Tag table.
从“按标记统计”表中排除这些标记
--tagstatcombine <tags:title>
 Creates combined statistics based on tags.
基于标记创建组合统计信息。
--tagdoc <pattern:doc>
 Adds documentation to the specified tags.
将文档添加到指定的标记
--tagstatlink <pattern:link:title>
 Adds external links to the Statistics by Tag table.
外部链接添加到“按标记统计”表中。
--expandkeywords <name:pattern|tag:pattern>
 Automatically expand keywords in the generated log file.
在生成的日志文件中自动展开关键字
--removekeywords <all|passed|name:pattern|tag:pattern|for|wuks>
 Removes keyword data from the generated outputs.
从生成的输出中删除关键字数据
--flattenkeywords <for|foritem|name:pattern|tag:pattern>
 Flattens keywords in the generated outputs.
在生成的输出中展平关键字
--starttime <timestamp>
 Sets the starting time of test execution when creating reports.
在创建报告时设置测试执行的开始时间
--endtime <timestamp>
 Sets the ending time of test execution when creating reports.
在创建报告时设置测试执行的结束时间
--nostatusrc Sets the return code to zero regardless of failures in test cases. Error codes are returned normally.
返回代码设置为零,而不管测试用例中是否失败。错误代码正常返回。
--processemptysuite
 Processes output files even if files contain empty test suites.
处理输出文件,即使文件包含空的测试套件
--prerebotmodifier <name:args>
 Activate programmatic modification of results.
激活结果的程序化修改
-C, --consolecolors <auto|on|ansi|off>
 Specifies are colors used on the console.
指定控制台上使用的颜色。
-P, --pythonpath <path>
 Additional locations to add to the module search path.
要添加到模块搜索路径的其他位置。
-A, --argumentfile <path>
 A text file to read more arguments from.
一个文本文件,用于读取更多参数
-h, --help Prints usage instructions.
打印使用说明
--version Prints the version information.
打印版本信息

6.2.3   Environment variables for execution and post-processing
6.2.3执行和后处理的环境变量

ROBOT_OPTIONS and REBOT_OPTIONS  ROBOT_OPTIONSREBOT_OPTIONS
Space separated list of default options to be placed in front of any explicit options on the command line.
要放在命令行上任何显式选项前面的以空格分隔的默认选项列表。
ROBOT_SYSLOG_FILE
Path to a syslog file where Robot Framework writes internal information about parsing test case files and running tests.
系统日志文件的路径,Robot Framework在其中写入有关分析测试用例文件和运行测试的内部信息。
ROBOT_SYSLOG_LEVEL
Log level to use when writing to the syslog file.
写入系统日志文件时使用的日志级别。
ROBOT_INTERNAL_TRACES
When set to any non-empty value, Robot Framework's internal methods are included in error tracebacks.
当设置为任何非空值时,Robot Framework的内部方法将包含在错误跟踪中。

6.3   Translations 6.3翻译

Robot Framework supports translating section headers, settings, Given/When/Then prefixes used in Behavior Driven Development (BDD) as well as true and false strings used in automatic Boolean argument conversion. This appendix lists all translations for all languages, excluding English, that Robot Framework supports out-of-the-box.
Robot Framework支持翻译节头设置、行为驱动开发(BDD)中使用的Given/When/Then前缀以及自动布尔参数转换中使用的true和false字符串。本附录列出了Robot Framework开箱即用支持的所有语言(英语除外)的所有翻译。

How to actually activate translations is explained in the Localization section. That section also explains how to create custom language definitions and how to contribute new translations.
如何实际激活翻译将在本地化部分进行解释。该部分还解释了如何创建自定义语言定义以及如何贡献新的翻译。

6.3.1   Bulgarian (bg) 6.3.1保加利亚语

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Настройки 自定义设置
Variables 变量 Променливи Promenlivi
Test Cases 测试案例 Тестови случаи 测试案例数
Tasks 任务 Задачи 挑战:挑战
Keywords 关键词 Ключови думи 钥匙Dumi
Comments 评论 Коментари 评论家们

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 Библиотека 图书馆图书馆
Resource 资源 Ресурс 资源:资源
Variables 变量 Променлива Promeneliva
Name 名称  
Documentation 文件 Документация D.文件/
Metadata 元数据 Метаданни 元丹尼
Suite Setup 套件安装程序 Първоначални настройки на комплекта
设置设置开始在套件上
Suite Teardown Teardown套房 Приключване на комплекта 在套件中冒险
Test Setup 测试设置。 Първоначални настройки на тестове
在测试中开始设置
Task Setup 任务设置程序 Първоначални настройки на задачи
从任务开始设置设置
Test Teardown 撕裂测试仪 Приключване на тестове 在测试中冒险
Task Teardown 任务撕裂(英语:Task Teardown) Приключване на задачи 冒险去挑战。
Test Template 测试模板 Шаблон за тестове 一个测试模板
Task Template 任务模板 Шаблон за задачи 按任务设置模板
Test Timeout 测试超时 Таймаут за тестове 在测试中的计时
Task Timeout 任务超时 Таймаут за задачи 时间表的任务
Test Tags 测试标签 Етикети за тестове Yetiketi测试
Task Tags 任务标记 Етикети за задачи Yetiketi的任务
Keyword Tags 关键字标签 Етикети за ключови думи Yetiketi的钥匙杜米
Tags 标签 Етикети Yetiketi
Setup 设置 Първоначални настройки 自定义开始设置
Teardown Приключване 一个冒险家
Template 模板 Шаблон 关于模板的说明
Timeout 超时 Таймаут 时间表:
Arguments 论点 Аргументи 阿尔古门蒂

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 В случай че 在e的情况下
When  Когато 科加托
Then 然后 Тогава Togawa
And  И
But  Но 但是,

Boolean strings 布尔字符串

True/False 真/假 Values 
True  Вярно, Да, Включен 打开,是,打开
False  Невярно, Не, Изключен, Нищо
软,不,关闭,Nishcho

6.3.2   Bosnian (bs) 6.3.2波斯尼亚语(bs)

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Postavke
Variables 变量 Varijable 可变的
Test Cases 测试案例 Test Cases 测试案例
Tasks 任务 Taskovi 塔斯科维奇
Keywords 关键词 Keywords 关键词
Comments 评论 Komentari 科门塔里

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 Biblioteka
Resource 资源 Resursi 雷苏尔西
Variables 变量 Varijable 可变的
Name 名称  
Documentation 文件 Dokumentacija
Metadata 元数据 Metadata 元数据
Suite Setup 套件安装程序 Suite Postavke Postavke套房
Suite Teardown Teardown套房 Suite Teardown Teardown套房
Test Setup 测试设置。 Test Postavke Postavke测试
Task Setup 任务设置程序 Task Postavke Postavke任务
Test Teardown 撕裂测试仪 Test Teardown 撕裂测试仪
Task Teardown 任务撕裂(英语:Task Teardown) Task Teardown 任务撕裂(英语:Task Teardown)
Test Template 测试模板 Test Template 测试模板
Task Template 任务模板 Task Template 任务模板
Test Timeout 测试超时 Test Timeout 测试超时
Task Timeout 任务超时 Task Timeout 任务超时
Test Tags 测试标签 Test Tagovi 测试tasovi
Task Tags 任务标记 Task Tagovi 塔戈维任务
Keyword Tags 关键字标签 Keyword Tagovi 关键词Tagovi
Tags 标签 Tagovi 塔戈维
Setup 设置 Postavke
Teardown Teardown
Template 模板 Template 模板
Timeout 超时 Timeout 超时
Arguments 论点 Argumenti 阿尔古门蒂

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 Uslovno 乌斯洛夫诺
When  Kada 卡田
Then 然后 Tada
And  I
But  Ali 阿里

Boolean strings 布尔字符串

True/False 真/假 Values 
True   
False   

6.3.3   Czech (cs) 6.3.3捷克语

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Nastavení 纳斯塔维尼
Variables 变量 Proměnné 普罗梅内
Test Cases 测试案例 Testovací případy
Tasks 任务 Úlohy 乌洛希
Keywords 关键词 Klíčová slova 克利乔娃·斯洛娃
Comments 评论 Komentáře 科门塔热

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 Knihovna 克尼霍夫纳
Resource 资源 Zdroj 兹德罗伊
Variables 变量 Proměnná 我保证
Name 名称 Název 纳兹夫
Documentation 文件 Dokumentace
Metadata 元数据 Metadata 元数据
Suite Setup 套件安装程序 Příprava sady 饰Prava Sady
Suite Teardown Teardown套房 Ukončení sady 郑秀文sady
Test Setup 测试设置。 Příprava testu 饰Testu
Task Setup 任务设置程序 Příprava úlohy 普日普拉瓦·乌洛伊
Test Teardown 撕裂测试仪 Ukončení testu 你的考验
Task Teardown 任务撕裂(英语:Task Teardown) Ukončení úlohy 乌可涅乌西
Test Template 测试模板 Šablona testu 萨布洛娜睾丸
Task Template 任务模板 Šablona úlohy 莎布洛娜·尤洛伊
Test Timeout 测试超时 Časový limit testu 查索维极限测试
Task Timeout 任务超时 Časový limit úlohy 查索维限制所有权利
Test Tags 测试标签 Štítky testů 关于试验
Task Tags 任务标记 Štítky úloh 饰Kylie Uloh..
Keyword Tags 关键字标签 Štítky klíčových slov 斯洛夫斯基Klíčovich
Tags 标签 Štítky 饰Sytky
Setup 设置 Příprava 布拉格
Teardown Ukončení Ukonne的
Template 模板 Šablona 沙巴隆
Timeout 超时 Časový limit 恰索夫列极限
Arguments 论点 Argumenty 阿尔古门蒂

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 Pokud Pokud。
When  Když Kdy
Then 然后 Pak 他说:"我认为这是一个很好的机会,让人们了解我们的文化,了解我们是谁。
And  A
But  Ale

Boolean strings 布尔字符串

True/False 真/假 Values 
True  Pravda, Ano, Zapnuto Pravda,Ano,Zapnuto,阿纳乌
False  Nepravda, Ne, Vypnuto, Nic
Nepravda,Ne,Vypnuto,Nic

6.3.4   German (de) 6.3.4德语(de)

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Einstellungen 态度
Variables 变量 Variablen 变量
Test Cases 测试案例 Testfälle test案例
Tasks 任务 Aufgaben tags任务
Keywords 关键词 Schlüsselwörter 关键词
Comments 评论 Kommentare 评论

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 Bibliothek 图书馆
Resource 资源 Ressource 资源
Variables 变量 Variablen 变量
Name 名称 Name 名称
Documentation 文件 Dokumentation documentation文件
Metadata 元数据 Metadaten metadata元数据
Suite Setup 套件安装程序 Suitevorbereitung 准备套装
Suite Teardown Teardown套房 Suitenachbereitung 汤品准备
Test Setup 测试设置。 Testvorbereitung 测试准备
Task Setup 任务设置程序 Aufgabenvorbereitung 任务准备
Test Teardown 撕裂测试仪 Testnachbereitung 测试后处理
Task Teardown 任务撕裂(英语:Task Teardown) Aufgabennachbereitung 任务准备
Test Template 测试模板 Testvorlage test介绍
Task Template 任务模板 Aufgabenvorlage 任务介绍
Test Timeout 测试超时 Testzeitlimit 测试时限
Task Timeout 任务超时 Aufgabenzeitlimit 任务时限
Test Tags 测试标签 Testmarker 测试标记
Task Tags 任务标记 Aufgabenmarker 任务Mark
Keyword Tags 关键字标签 Schlüsselwortmarker 关键词Mark
Tags 标签 Marker
Setup 设置 Vorbereitung 筹备
Teardown Nachbereitung 跟踪
Template 模板 Vorlage 介绍介绍
Timeout 超时 Zeitlimit 时限
Arguments 论点 Argumente arguments论据

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 Angenommen 假设
When  Wenn if
Then 然后 Dann 然后
And  Und 
But  Aber 但是

Boolean strings 布尔字符串

True/False 真/假 Values 
True  Wahr, Ja, An, Ein Yes,yes,an,是的,是的
False  Falsch, Nein, Aus, Unwahr
假的,不,假的,假的

6.3.5   Spanish (es) 6.3.5西班牙语(es)

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Configuraciones 配置配置
Variables 变量 Variables 变量
Test Cases 测试案例 Casos de prueba 测试案例
Tasks 任务 Tareas 任务
Keywords 关键词 Palabras clave 关键词
Comments 评论 Comentarios 评论

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 Biblioteca 图书馆
Resource 资源 Recursos 资源
Variables 变量 Variable 可变
Name 名称 Nombre 名称
Documentation 文件 Documentación 文件
Metadata 元数据 Metadatos 元数据
Suite Setup 套件安装程序 Configuración de la Suite
套件的配置
Suite Teardown Teardown套房 Desmontaje de la Suite 套件的拆卸
Test Setup 测试设置。 Configuración de prueba 测试配置
Task Setup 任务设置程序 Configuración de tarea 任务配置
Test Teardown 撕裂测试仪 Desmontaje de la prueba 测试的拆卸
Task Teardown 任务撕裂(英语:Task Teardown) Desmontaje de tareas 任务的拆卸
Test Template 测试模板 Plantilla de prueba 测试的模板
Task Template 任务模板 Plantilla de tareas 任务的模板
Test Timeout 测试超时 Tiempo de espera de la prueba
测试的等待时间
Task Timeout 任务超时 Tiempo de espera de las tareas
任务的等待时间
Test Tags 测试标签 Etiquetas de la prueba 测试的标签
Task Tags 任务标记 Etiquetas de las tareas 任务的标签
Keyword Tags 关键字标签 Etiquetas de palabras clave
关键字标签
Tags 标签 Etiquetas 标签
Setup 设置 Configuración 配置
Teardown Desmontaje 拆卸
Template 模板 Plantilla
Timeout 超时 Tiempo agotado 耗尽时间
Arguments 论点 Argumentos Arguments

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 Dado 给予
When  Cuando 
Then 然后 Entonces 然后
And  Y
But  Pero 但是

Boolean strings 布尔字符串

True/False 真/假 Values 
True  Verdadero, Si, On 真,是,开
False  Falso, No, Off, Ninguno 不,不

6.3.6   Finnish (fi) 6.3.6芬兰语(fi)

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Asetukset tukset
Variables 变量 Muuttujat 穆穆穆
Test Cases 测试案例 Testit 作证
Tasks 任务 Tehtävät 迟鹏
Keywords 关键词 Avainsanat avainsanat的
Comments 评论 Kommentit 评论

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 Kirjasto
Resource 资源 Resurssi
Variables 变量 Muuttujat
Name 名称 Nimi
Documentation 文件 Dokumentaatio 文献
Metadata 元数据 Metatiedot Metatiedot的
Suite Setup 套件安装程序 Setin Alustus 饰Setin Alustus
Suite Teardown Teardown套房 Setin Alasajo 饰Setin Alasajo
Test Setup 测试设置。 Testin Alustus 测试Alustus
Task Setup 任务设置程序 Tehtävän Alustus 曲名:Alustus
Test Teardown 撕裂测试仪 Testin Alasajo 考试Alasajo
Task Teardown 任务撕裂(英语:Task Teardown) Tehtävän Alasajo 阿拉斯加之行Alasajo
Test Template 测试模板 Testin Malli 测试员Malli
Task Template 任务模板 Tehtävän Malli 饰Malli
Test Timeout 测试超时 Testin Aikaraja 测试Aikaraja
Task Timeout 任务超时 Tehtävän Aikaraja 饰Aikaraja
Test Tags 测试标签 Testin Tagit 测试Tagit
Task Tags 任务标记 Tehtävän Tagit 饰Tagit
Keyword Tags 关键字标签 Avainsanan Tagit
Tags 标签 Tagit tagit标签
Setup 设置 Alustus
Teardown Alasajo
Template 模板 Malli Malli。
Timeout 超时 Aikaraja
Arguments 论点 Argumentit 论证

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 Oletetaan
When  Kun Kun.
Then 然后 Niin 尼因(Nin)
And  Ja 如果你是一个人,
But  Mutta 穆塔(Mutta)

Boolean strings 布尔字符串

True/False 真/假 Values 
True  Tosi, Kyllä, Päällä 对不起,Kylar,对不起。
False  Epätosi, Ei, Pois 不,不,不。

6.3.7   French (fr) 6.3.7法语(fr)

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Paramètres 参数
Variables 变量 Variables 变量
Test Cases 测试案例 Unités de test 试验单位
Tasks 任务 Tâches 任务
Keywords 关键词 Mots-clés 关键词
Comments 评论 Commentaires 注释

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 Bibliothèque 图书馆
Resource 资源 Ressource 资源
Variables 变量 Variable 可变
Name 名称 Nom 名称
Documentation 文件 Documentation 文件
Metadata 元数据 Méta-donnée 元数据
Suite Setup 套件安装程序 Mise en place de suite
套件的设置
Suite Teardown Teardown套房 Démontage de suite 拆卸套件
Test Setup 测试设置。 Mise en place de test
测试的设置
Task Setup 任务设置程序 Mise en place de tâche
任务的设置
Test Teardown 撕裂测试仪 Démontage de test 拆卸测试
Task Teardown 任务撕裂(英语:Task Teardown) Démontage de test 拆卸测试
Test Template 测试模板 Modèle de test 测试模型
Task Template 任务模板 Modèle de tâche 任务模型
Test Timeout 测试超时 Délai de test 测试截止日期
Task Timeout 任务超时 Délai de tâche 任务截止日期
Test Tags 测试标签 Étiquette de test 测试标签
Task Tags 任务标记 Étiquette de tâche 任务标签
Keyword Tags 关键字标签 Etiquette de mot-clé 标签关键字
Tags 标签 Étiquette 标签
Setup 设置 Mise en place 设置到位
Teardown Démontage 拆卸
Template 模板 Modèle 模型
Timeout 超时 Délai d'attente 等待时间
Arguments 论点 Arguments 论点

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 Étant donné 被给予
When  Lorsque 
Then 然后 Alors 因此
And  Et 
But  Mais 但是

Boolean strings 布尔字符串

True/False 真/假 Values 
True  Vrai, Oui, Actif 是的,活动
False  Faux, Non, Désactivé, Aucun
错误、否、禁用、无

6.3.8   Hindi (hi) 6.3.8印地语(高)

Section headers 节标题

Header 标题 Translation 翻译
Settings 设置 स्थापना
Variables 变量 चर
Test Cases 测试案例 नियत कार्य प्रवेशिका 重试    错误原因
Tasks 任务 कार्य प्रवेशिका
Keywords 关键词 कुंजीशब्द
Comments 评论 टिप्पणी

Settings 设置

Setting 设置 Translation 翻译
Library 图书馆 कोड़ प्रतिबिंब संग्रह 重试    错误原因
Resource 重试    错误原因 संसाधन 重试    错误原因
Variables 重试    错误原因 चर 重试    错误原因
Name 名称  
Documentation 文件 प्रलेखन 重试    错误原因
Metadata 重试    错误原因 अधि-आंकड़ा 重试    错误原因
Suite Setup 重试    错误原因 जांच की शुरुवात 重试    错误原因
Suite Teardown 重试    错误原因 परीक्षण कार्य अंत 重试    错误原因
Test Setup 测试设置 परीक्षण कार्य प्रारंभ 重试    错误原因
Task Setup 任务设置程序 परीक्षण कार्य प्रारंभ 重试    错误原因
Test Teardown 撕裂测试仪 परीक्षण कार्य अंत 重试    错误原因
Task Teardown 任务撕裂(英语:Task Teardown) परीक्षण कार्य अंत 重试    错误原因
Test Template 测试模板 परीक्षण ढांचा 重试    错误原因
Task Template 任务模板 परीक्षण ढांचा 重试    错误原因
Test Timeout 测试超时 परीक्षण कार्य समय समाप्त 重试    错误原因
Task Timeout 任务超时 कार्य समयबाह्य 重试    错误原因
Test Tags 测试标签 जाँचका उपनाम 重试    错误原因
Task Tags 任务标记 कार्यका उपनाम 重试    错误原因
Keyword Tags 关键字标签 कुंजीशब्द का उपनाम 重试    错误原因
Tags 标签 निशान 重试    错误原因
Setup 设置 व्यवस्थापना 重试    错误原因
Teardown विमोचन 重试    错误原因
Template 模板 साँचा 重试    错误原因
Timeout 超时 समय समाप्त 重试    错误原因
Arguments 论点 प्राचल 重试    错误原因

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 दिया हुआ 重试    错误原因
When  जब 重试    错误原因
Then 然后 तब 重试    错误原因
And  और 重试    错误原因
But  परंतु 重试    错误原因

Boolean strings 布尔字符串

True/False 真/假 Values 
True  यथार्थ, निश्चित, हां, पर 重试    错误原因
False  गलत, नहीं, हालाँकि, यद्यपि, नहीं, हैं 重试    错误原因

6.3.9   Italian (it) 6.3.9意大利语(it)

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Impostazioni Approxes
Variables 变量 Variabili 变量
Test Cases 测试案例 Casi Di Test Case测试
Tasks 任务 Attività Activities
Keywords 关键词 Parole Chiave 关键词
Comments 评论 Commenti 评论

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 Libreria 书店
Resource 资源 Risorsa 资源
Variables 变量 Variabile 变量
Name 名称 Nome 姓名
Documentation 文件 Documentazione 文件文件
Metadata 元数据 Metadati Metadata
Suite Setup 套件安装程序 Configurazione Suite Suite的设定
Suite Teardown Teardown套房 Distruzione Suite 破坏套房
Test Setup 测试设置。 Configurazione Test 配置Test
Task Setup 任务设置程序 Configurazione Attività 活动configuration
Test Teardown 撕裂测试仪 Distruzione Test 销毁测试
Task Teardown 任务撕裂(英语:Task Teardown) Distruzione Attività 销毁活动
Test Template 测试模板 Modello Test 模型测试
Task Template 任务模板 Modello Attività 活动模式
Test Timeout 测试超时 Timeout Test Timeout测试
Task Timeout 任务超时 Timeout Attività 活动Timeout
Test Tags 测试标签 Tag Del Test Tag测试
Task Tags 任务标记 Tag Attività Tag活动
Keyword Tags 关键字标签 Tag Parola Chiave Tag关键词
Tags 标签 Tag
Setup 设置 Configurazione configuration的
Teardown Distruzione 销毁
Template 模板 Template 模板
Timeout 超时 Timeout 超时
Arguments 论点 Parametri 参数

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 Dato Dato数据
When  Quando 何时
Then 然后 Allora 那么
And  E
But  Ma 但是

Boolean strings 布尔字符串

True/False 真/假 Values 
True  Vero, Sì, On 是的,是的,On
False  Falso, No, Off, Nessuno 别名:Off,No,No,No

6.3.10   Japanese (ja) 6.3.10日语(ja)

New in Robot Framework 7.0.1.
Robot Framework 7.0.1中的新功能。

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 設定
Variables 变量 変数
Test Cases 测试案例 テスト ケース 测试用例(Test Case)
Tasks 任务 タスク Task(任务)
Keywords 关键词 キーワード 关键字(Keyword)
Comments 评论 コメント Comments(注释)

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 ライブラリ Library(库)
Resource 资源 リソース Resources(资源)
Variables 变量 変数
Name 名称 名前
Documentation 文件 ドキュメント 文档(Document)
Metadata 元数据 メタデータ 元数据(Metadata)
Suite Setup 套件安装程序 スイート セットアップ 套件设置(Suite Setup)
Suite Teardown Teardown套房 スイート ティアダウン Suite Tier Down
Test Setup 测试设置。 テスト セットアップ Test Setup(测试设置)
Task Setup 任务设置程序 タスク セットアップ 任务设置(Task Setup)
Test Teardown 撕裂测试仪 テスト ティアダウン 测试撕裂(Test Tier Down)
Task Teardown 任务撕裂(英语:Task Teardown) タスク ティアダウン 任务拆分(Task Tier Down)
Test Template 测试模板 テスト テンプレート Test Template(测试模板)
Task Template 任务模板 タスク テンプレート 任务模板(Task Template)
Test Timeout 测试超时 テスト タイムアウト Test Timeout(测试超时)
Task Timeout 任务超时 タスク タイムアウト 任务超时(Task Timeout)
Test Tags 测试标签 テスト タグ 测试标记(Test Tag)
Task Tags 任务标记 タスク タグ 任务标记(Task Tag)
Keyword Tags 关键字标签 キーワード タグ 关键字标记(Keyword Tag)
Tags 标签 タグ Tag(Tag)
Setup 设置 セットアップ Setup(设置)
Teardown ティアダウン 分层(TiDown)
Template 模板 テンプレート Template(Template)
Timeout 超时 タイムアウト 超时(Timeout)
Arguments 论点 引数

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 仮定, 指定, 前提条件
When  条件, 次の場合, もし, 実行条件 条件,在下一个情况下,如果,执行条件
Then 然后 アクション, その時, 動作 行动,然后,行动。
And  および, 及び, かつ, 且つ, ならびに, 並びに, そして, それから
然后,然后。
But  ただし, 但し 然而,尽管

Boolean strings 布尔字符串

True/False Values
True 真, 有効, はい, オン 真的,有效的,是的。
False 偽, 無効, いいえ, オフ 假的,无效的,关闭

6.3.11   Dutch (nl) 6.3.11荷兰语(nl)

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Instellingen 因斯特林根
Variables 变量 Variabelen 瓦里亚贝伦
Test Cases 测试案例 Testgevallen 泰斯特格瓦伦
Tasks 任务 Taken 采取
Keywords 关键词 Sleutelwoorden 斯吕特尔伍登
Comments 评论 Opmerkingen 奥普梅尔金根

Settings 设置

Setting 设置 Translation 翻译
Library 图书馆 Bibliotheek
Resource 资源 Resource 资源
Variables 变量 Variabele 变量
Name 名称 Naam
Documentation 文件 Documentatie 文件
Metadata 元数据 Metadata 元数据
Suite Setup 套件安装程序 Suite Preconditie 套房先决条件
Suite Teardown Teardown套房 Suite Postconditie 套房后置
Test Setup 测试设置。 Test Preconditie 测试前提条件
Task Setup 任务设置程序 Taak Preconditie Taak前提条件
Test Teardown 撕裂测试仪 Test Postconditie 测试后条件
Task Teardown 任务撕裂(英语:Task Teardown) Taak Postconditie 塔克·波斯康迪蒂
Test Template Test Sjabloon
Task Template 任务template Taak Sjabloon Taak Sjabloon的评论
Test Timeout 测试超时 Test Time-out 测试Time—out
Task Timeout task timeout任务超时 Taak Time-out 超时Taak Time—Out
Test Tags 测试标签 Test Labels 测试Labels
Task Tags tags任务 Taak Labels TAAK标签
Keyword Tags 关键词Tags Sleutelwoord Labels Sleutelwoord Labels(斯雷特伍德标签)
Tags 标签 Labels 标签
Setup 设置 Preconditie 先决条件
Teardown Postconditie 后置条件
Template 模板 Sjabloon 夏布
Timeout 超时 Time-out 超时
Arguments 论点 Parameters 参数

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译
Given 给定 Stel, Gegeven Stel,Gegeven
When  Als
Then 然后 Dan 
And  En
But  Maar 玛珥

Boolean strings 布尔字符串

True/False True/False的 Values 价值观
True Waar, Ja, Aan 是是是
False Onwaar, Nee, Uit, Geen 不,不。

6.3.12   Polish (pl)

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Ustawienia 乌斯塔维尼亚
Variables 变量 Zmienne 兹米纳
Test Cases 测试案例 Przypadki Testowe 普日帕德基·泰斯托韦
Tasks 任务 Zadania 扎达尼亚
Keywords 关键词 Słowa Kluczowe 圣克卢佐韦
Comments 评论 Komentarze 科门塔尔泽

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 Biblioteka
Resource 资源部 Zasób 扎索布
Variables 变量 Zmienne 兹米纳
Name 名称 Nazwa
Documentation 文件 Dokumentacja
Metadata 元数据 Metadane
Suite Setup 套件安装程序 Inicjalizacja Zestawu
Suite Teardown Teardown套房 Ukończenie Zestawu
Test Setup 测试设置。 Inicjalizacja Testu
Task Setup 任务设置程序 Inicjalizacja Zadania
Test Teardown 撕裂测试仪 Ukończenie Testu
Task Teardown 任务撕裂(英语:Task Teardown) Ukończenie Zadania Ukoinczenie Zadania
Test Template 测试模板 Szablon Testu
Task Template 任务template Szablon Zadania 扎达尼亚Zadania
Test Timeout 测试超时 Limit Czasowy Testu Czasovy Testu限制
Task Timeout task timeout任务超时 Limit Czasowy Zadania 卡扎佐夫Zadania
Test Tags 测试标签 Znaczniki Testu znaczniki测试
Task Tags tags任务 Znaczniki Zadania znaczniki扎达尼亚
Keyword Tags 关键词Tags Znaczniki Słowa Kluczowego
斯沃沃瓦Kluczowego
Tags 标签 Znaczniki znaczniki的
Setup Inicjalizacja Inicjalizacja的
Teardown Teardown文件 Ukończenie Ukończenie的
Template 模板 Szablon 绍布隆
Timeout 超时 Limit Czasowy 利米茨·恰索维
Arguments 论点 Argumenty 阿尔古门蒂

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 Zakładając, Zakładając, że, Mając
扎卡里阿达杰茨,马杰茨
When  Jeżeli, Jeśli, Gdy, Kiedy
Jejeli,Jejeli,Gdy,Kiedy
Then 然后 Wtedy 弗泰迪
And  Oraz, I 奥拉兹岛
But  Ale

Boolean strings 布尔字符串

True/False 真/假 Values 
True  Prawda, Tak, Włączone 普拉达、塔克、韦什托佐内
False  Fałsz, Nie, Wyłączone, Nic
不,不,不。

6.3.13   Portuguese (pt)

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Definições 定义
Variables 变量 Variáveis Variable变量
Test Cases 测试案例 Casos de Teste 测试案例
Tasks 任务 Tarefas tags
Keywords 关键词 Palavras-Chave 关键词
Comments 评论 Comentários 评论

Settings 设定值

Setting 设置 Translation 翻译的
Library 图书馆 Biblioteca 图书馆
Resource 资源 Recurso 资源
Variables 变量 Variável Variable变量
Name 名称 Nome 姓名
Documentation 文件 Documentação Documentation文件
Metadata 元数据 Metadados 金属
Suite Setup 套件安装程序 Inicialização de Suíte 11.寿司的开始
Suite Teardown Teardown套房 Finalização de Suíte 完结寿司
Test Setup Inicialização de Teste
Task Setup Inicialização de Tarefa
Test Teardown Finalização de Teste
Task Teardown Finalização de Tarefa
Test Template Modelo de Teste
Task Template Modelo de Tarefa
Test Timeout Tempo Limite de Teste
Task Timeout Tempo Limite de Tarefa
Test Tags Etiquetas de Testes
Task Tags Etiquetas de Tarefas
Keyword Tags Etiquetas de Palavras-Chave
Tags Etiquetas
Setup Inicialização
Teardown Finalização
Template Modelo
Timeout Tempo Limite
Arguments Argumentos

BDD prefixes

Prefix Translation
Given Dado
When Quando
Then Então
And E
But Mas

Boolean strings

True/False Values
True Verdadeiro, Verdade, Sim, Ligado
False Falso, Não, Desligado, Desativado, Nada

6.3.14   Brazilian Portuguese (pt-BR)

Section headers

Header Translation
Settings Configurações
Variables Variáveis
Test Cases Casos de Teste
Tasks Tarefas
Keywords Palavras-Chave
Comments Comentários

Settings

Setting Translation
Library Biblioteca
Resource Recurso
Variables Variável
Name Nome
Documentation Documentação
Metadata Metadados
Suite Setup Configuração da Suíte
Suite Teardown Finalização de Suíte
Test Setup Inicialização de Teste
Task Setup Inicialização de Tarefa
Test Teardown Finalização de Teste
Task Teardown Finalização de Tarefa
Test Template Modelo de Teste
Task Template Modelo de Tarefa
Test Timeout Tempo Limite de Teste
Task Timeout Tempo Limite de Tarefa
Test Tags Test Tags
Task Tags Task Tags
Keyword Tags Keyword Tags
Tags Etiquetas
Setup Inicialização
Teardown Finalização
Template Modelo
Timeout Tempo Limite
Arguments Argumentos

BDD prefixes

Prefix Translation
Given Dado
When Quando
Then Então
And E
But Mas

Boolean strings

True/False Values
True Verdadeiro, Verdade, Sim, Ligado
False Falso, Não, Desligado, Desativado, Nada

6.3.15   Romanian (ro)

Section headers

Header Translation
Settings Setari
Variables Variabile
Test Cases Cazuri De Test
Tasks Sarcini
Keywords Cuvinte Cheie
Comments Comentarii

Settings

Setting Translation
Library Librarie
Resource Resursa
Variables Variabila
Name Nume
Documentation Documentatie
Metadata Metadate
Suite Setup Configurare De Suita
Suite Teardown Configurare De Intrerupere
Test Setup Setare De Test
Task Setup Configuarare activitate
Test Teardown Inrerupere De Test
Task Teardown Intrerupere activitate
Test Template Sablon De Test
Task Template Sablon de activitate
Test Timeout Timp Expirare Test
Task Timeout Timp de expirare activitate
Test Tags Taguri De Test
Task Tags Etichete activitate
Keyword Tags Etichete metode
Tags Etichete
Setup Setare
Teardown Intrerupere
Template Sablon
Timeout Expirare
Arguments Argumente

BDD prefixes

Prefix Translation
Given Fie ca
When Cand
Then Atunci
And Si
But Dar

Boolean strings

True/False Values
True Adevarat, Da, Cand
False Fals, Nu, Oprit, Niciun

6.3.16   Russian (ru)

Section headers

Header Translation
Settings Настройки
Variables Переменные
Test Cases Заголовки тестов
Tasks Задача
Keywords Ключевые слова
Comments Комментарии

Settings

Setting Translation
Library Библиотека
Resource Ресурс
Variables Переменные
Name  
Documentation Документация
Metadata Метаданные
Suite Setup Инициализация комплекта тестов
Suite Teardown Завершение комплекта тестов
Test Setup Инициализация теста
Task Setup Инициализация задания
Test Teardown Завершение теста
Task Teardown Завершение задания
Test Template Шаблон теста
Task Template Шаблон задания
Test Timeout Лимит выполнения теста
Task Timeout Лимит задания
Test Tags Теги тестов
Task Tags Метки заданий
Keyword Tags Метки ключевых слов
Tags Метки
Setup Инициализация
Teardown Завершение
Template Шаблон
Timeout Лимит
Arguments Аргументы

BDD prefixes

Prefix Translation
Given Дано
When Когда
Then Тогда
And И
But Но

Boolean strings

True/False Values
True  
False  

6.3.17   Swedish (sv)

Section headers

Header Translation
Settings Inställningar
Variables Variabler
Test Cases Testfall
Tasks Taskar
Keywords Nyckelord
Comments Kommentarer

Settings

Setting Translation
Library Bibliotek
Resource Resurs
Variables Variabel
Name Namn
Documentation Dokumentation
Metadata Metadata
Suite Setup Svit konfigurering
Suite Teardown Svit nedrivning
Test Setup 测试设置 Test konfigurering 测试确认
Task Setup 任务设置 Task konfigurering 任务配置
Test Teardown 测试拆卸 Test nedrivning 测试驱动
Task Teardown 任务拆卸 Task nedrivning 任务驱动
Test Template 测试模板 Test mall 测试商城
Task Template 任务模板 Task mall 任务商城
Test Timeout 测试超时 Test timeout 测试超时
Task Timeout 任务超时 Task timeout 任务超时
Test Tags 测试标签 Test taggar 测试标签
Task Tags 任务标记 Arbetsuppgift taggar 阿贝苏普加勒
Keyword Tags 关键字标签 Nyckelord taggar 尼克洛·塔加尔
Tags 标签 Taggar 塔加尔
Setup 设置 Konfigurering 孔菲古雷林
Teardown Nedrivning 内德里夫宁
Template 模板 Mall 商城
Timeout 超时 Timeout 超时
Arguments 论点 Argument 论点

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译
Given 给定 Givet 吉维
When  När 纳尔
Then 然后  
And  Och
But  Men 男人

Boolean strings 布尔字符串

True/False 真/假 Values 
True  Sant, Ja, På 桑特角,印尼-地
False  Falskt, Nej, Av, Ingen 法尔斯克特、内季、亚夫、英根

6.3.18   Thai (th) 6.3.18泰文(th)

Section headers

Header Translation
Settings การตั้งค่า
Variables กำหนดตัวแปร
Test Cases การทดสอบ
Tasks งาน
Keywords คำสั่งเพิ่มเติม
Comments คำอธิบาย

Settings

Setting Translation
Library ชุดคำสั่งที่ใช้
Resource ไฟล์ที่ใช้
Variables ชุดตัวแปร
Name  
Documentation เอกสาร
Metadata รายละเอียดเพิ่มเติม
Suite Setup กำหนดค่าเริ่มต้นของชุดการทดสอบ
Suite Teardown คืนค่าของชุดการทดสอบ
Test Setup กำหนดค่าเริ่มต้นของการทดสอบ
Task Setup กำหนดค่าเริ่มต้นของงาน
Test Teardown คืนค่าของการทดสอบ
Task Teardown คืนค่าของงาน
Test Template โครงสร้างของการทดสอบ
Task Template โครงสร้างของงาน
Test Timeout เวลารอของการทดสอบ
Task Timeout เวลารอของงาน
Test Tags กลุ่มของการทดสอบ
Task Tags กลุ่มของงาน
Keyword Tags กลุ่มของคำสั่งเพิ่มเติม
Tags กลุ่ม
Setup กำหนดค่าเริ่มต้น
Teardown คืนค่า
Template โครงสร้าง
Timeout หมดเวลา
Arguments ค่าที่ส่งเข้ามา

BDD prefixes

Prefix Translation
Given กำหนดให้
When เมื่อ
Then ดังนั้น
And และ
But แต่

Boolean strings

True/False Values
True  
False  

6.3.19   Turkish (tr)

Section headers

Header Translation
Settings Ayarlar
Variables Değişkenler
Test Cases Test Durumları
Tasks Görevler
Keywords Anahtar Kelimeler
Comments Yorumlar

Settings

Setting Translation
Library Kütüphane
Resource Kaynak
Variables Değişkenler
Name  
Documentation Dokümantasyon
Metadata Üstveri
Suite Setup Takım Kurulumu
Suite Teardown Takım Bitişi
Test Setup Test Kurulumu
Task Setup Görev Kurulumu
Test Teardown Test Bitişi
Task Teardown Görev Bitişi
Test Template Test Taslağı
Task Template Görev Taslağı
Test Timeout Test Zaman Aşımı
Task Timeout Görev Zaman Aşımı
Test Tags Test Etiketleri
Task Tags Görev Etiketleri
Keyword Tags Anahtar Kelime Etiketleri
Tags Etiketler
Setup Kurulum
Teardown Bitiş
Template Taslak
Timeout Zaman Aşımı
Arguments Argümanlar

BDD prefixes

Prefix Translation
Given Diyelim ki
When Eğer ki
Then O zaman
And Ve
But Ancak

Boolean strings

True/False Values
True Doğru, Evet, Açik
False Yanliş, Hayir, Kapali

6.3.20   Ukrainian (uk)

Section headers

Header Translation
Settings Налаштування
Variables Змінні
Test Cases Тест-кейси
Tasks Завдань
Keywords Ключових слова
Comments Коментарів

Settings

Setting Translation
Library Бібліотека
Resource Ресурс
Variables Змінна
Name  
Documentation Документація
Metadata Метадані
Suite Setup Налаштування Suite
Suite Teardown Розбірка Suite
Test Setup Налаштування тесту
Task Setup Налаштування завдання
Test Teardown Розбирання тестy
Task Teardown Розбір завдання
Test Template Тестовий шаблон
Task Template Шаблон завдання
Test Timeout Час тестування
Task Timeout Час очікування завдання
Test Tags Тестові теги
Task Tags Теги завдань
Keyword Tags Теги ключових слів
Tags Теги
Setup Встановлення
Teardown Cпростовувати пункт за пунктом
Template Шаблон
Timeout Час вийшов
Arguments Аргументи

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 Дано
When  Коли
Then 然后 Тоді
And  Та
But  Але

Boolean strings 布尔字符串

True/False 真/假 Values 
True   
False   

6.3.21   Vietnamese (vi) 6.3.21越南语(vi)

New in Robot Framework 6.1.
机器人框架6.1中的新功能。

Section headers 节标题

Header 标题 Translation 翻译的
Settings 设定值 Cài Đặt 
Variables 变量 Các biến số Các bi n s
Test Cases 测试案例 Các kịch bản kiểm thử
Các k ch B n ki m th
Tasks 任务 Các nghiệm vụ 曹毅武
Keywords 关键词 Các từ khóa 察茨霍亚
Comments 评论 Các chú thích 蔡氏

Settings

Setting Translation
Library Thư viện
Resource Tài nguyên
Variables Biến số
Name Tên
Documentation Tài liệu hướng dẫn
Metadata Dữ liệu tham chiếu
Suite Setup Tiền thiết lập bộ kịch bản kiểm thử
Suite Teardown Hậu thiết lập bộ kịch bản kiểm thử
Test Setup Tiền thiết lập kịch bản kiểm thử
Task Setup Tiền thiểt lập nhiệm vụ
Test Teardown Hậu thiết lập kịch bản kiểm thử
Task Teardown Hậu thiết lập nhiệm vụ
Test Template Mẫu kịch bản kiểm thử
Task Template Mẫu nhiễm vụ
Test Timeout Thời gian chờ kịch bản kiểm thử
Task Timeout Thời gian chờ nhiệm vụ
Test Tags Các nhãn kịch bản kiểm thử
Task Tags Các nhãn nhiệm vụ
Keyword Tags Các từ khóa nhãn
Tags Các thẻ
Setup Tiền thiết lập
Teardown Hậu thiết lập
Template Mẫu
Timeout Thời gian chờ
Arguments Các đối số

BDD prefixes

Prefix Translation
Given Đã cho
When Khi
Then Thì
And
But Nhưng

Boolean strings

True/False Values
True Đúng, Vâng, Mở
False Sai, Không, Tắt, Không Có Gì

6.3.22   Chinese Simplified (zh-CN)

Section headers

Header Translation
Settings 设置
Variables 变量
Test Cases 用例
Tasks 任务
Keywords 关键字
Comments 备注

Settings

Setting Translation
Library 程序库
Resource 资源文件
Variables 变量文件
Name  
Documentation 说明
Metadata 元数据
Suite Setup 用例集启程
Suite Teardown 用例集终程
Test Setup 用例启程
Task Setup 任务启程
Test Teardown 用例终程
Task Teardown 任务终程
Test Template 用例模板
Task Template 任务模板
Test Timeout 用例超时
Task Timeout 任务超时
Test Tags 用例标签
Task Tags 任务标签
Keyword Tags 关键字标签
Tags 标签
Setup 启程
Teardown 终程
Template 模板
Timeout 超时
Arguments 参数

BDD prefixes

Prefix Translation
Given 假定
When
Then 那么
And 并且
But 但是

Boolean strings

True/False Values
True 真, 是, 开
False 假, 否, 关, 空

6.3.23   Chinese Traditional (zh-TW)

Section headers

Header Translation
Settings 設置
Variables 變量
Test Cases 案例
Tasks 任務
Keywords 關鍵字
Comments 備註

Settings

Setting Translation
Library 函式庫
Resource 資源文件
Variables 变量 變量文件
Name 名称  
Documentation 文件 說明
Metadata 元数据 元數據
Suite Setup 套件安装程序 測試套啟程
Suite Teardown Teardown套房 測試套終程
Test Setup 测试设置。 測試啟程
Task Setup 任务设置程序 任務啟程
Test Teardown 撕裂测试仪 測試終程
Task Teardown 任务撕裂(英语:Task Teardown) 任務終程
Test Template 测试模板 測試模板
Task Template 任务模板 任務模板
Test Timeout 测试超时 測試逾時
Task Timeout 任务超时 任務逾時
Test Tags 测试标签 測試標籤
Task Tags 任务标记 任務標籤
Keyword Tags 关键字标签 關鍵字標籤
Tags 标签 標籤
Setup 设置 啟程
Teardown 終程
Template 模板 模板
Timeout 超时 逾時
Arguments 论点 参数

BDD prefixes BDD前缀

Prefix 前缀 Translation 翻译的
Given 给定 假定
When 
Then 然后 那麼
And 並且
But 但是

Boolean strings

True/False Values
True 真, 是, 開
False  假, 否, 關, 空

6.4   Documentation formatting
6.4文件格式

It is possible to use simple HTML formatting with test suite, test case and user keyword documentation and free suite metadata in the test data, as well as when documenting test libraries. The formatting is similar to the style used in most wikis, and it is designed to be understandable both as plain text and after the HTML transformation.
可以使用简单的HTML格式化测试套件测试用例用户关键字文档以及测试数据中的自由套件元数据,以及记录测试库时。格式与大多数wiki中使用的样式相似,并且它被设计为纯文本和HTML转换后都可以理解。

6.4.1   Handling whitespace in test data

Newlines

When documenting test suites, test cases and user keywords or adding metadata to test suites, newlines can be added manually using \n escape sequence.

*** Settings ***
Documentation    First line.\n\nSecond paragraph. This time\nwith multiple lines.
Metadata         Example list    - first item\n- second item\n- third

Note

As explained in the Paragraphs section below, the single newline in Second paragraph, this time\nwith multiple lines. does not actually affect how that paragraph is rendered. Newlines are needed when creating lists or other such constructs, though.

Adding newlines manually to a long documentation takes some effort and extra characters also make the documentation harder to read. This can be avoided, though, as newlines are inserted automatically between continued documentation and metadata lines. In practice this means that the above example could be written also as follows.

*** Settings ***
Documentation
...    First line.
...
...    Second paragraph. This time
...    with multiple lines.
Metadata
...    Example list
...    - first item
...    - second item
...    - third

No automatic newline is added if a line already ends with a literal newline or if it ends with an escaping backslash:

*** Test Cases ***
Ends with newline
    [Documentation]    Ends with a newline and\n
    ...                automatic newline is not added.

Ends with backslash
    [Documentation]    Ends with a backslash and \
    ...                no newline is added.

Spaces

Unlike elsewhere in Robot Framework data, leading spaces and consecutive internal spaces are preserved in documentation and metadata. This makes it possible, for example, to split list items to multiple rows and have preformatted text with spaces:

*** Test Cases ***
Long list item
    [Documentation]
    ...    List:
    ...    - Short item.
    ...    - Second item is pretty long and it is split to
    ...      multiple rows. Leading spaces are preserved.
    ...    - Another short item.

Preformatted text
    [Documentation]
    ...    Example with consecutive internal spaces:
    ...
    ...    | *** Test Cases ***
    ...    | Example
    ...    |     Keyword

Note

Preserving spaces in documentation and metadata is new in Robot Framework 6.1. With earlier versions spaces need to be escaped with a backslash.

6.4.2   Paragraphs

All regular text in the formatted HTML documentation is represented as paragraphs. In practice, lines separated by a single newline will be combined in a paragraph regardless whether the newline is added manually or automatically. Multiple paragraphs can be separated with an empty line (i.e. two newlines) and also tables, lists, and other specially formatted blocks discussed in subsequent sections end a paragraph.

For example, the following test suite or resource file documentation:

*** Settings ***
Documentation
...    First paragraph has only one line.
...
...    Second paragraph, this time created
...    with multiple lines.

will be formatted in HTML as:

First paragraph has only one line.

Second paragraph, this time created with multiple lines.

6.4.3   Inline styles

The documentation syntax supports inline styles bold, italic and code. Bold text can be created by having an asterisk before and after the selected word or words, for example *this is bold*. Italic style works similarly, but the special character to use is an underscore, for example, _italic_. It is also possible to have bold italic with the syntax _*bold italic*_.

The code style is created using double backticks like ``code``. The result is monospaced text with light gray background.

Asterisks, underscores or double backticks alone, or in the middle of a word, do not start formatting, but punctuation characters before or after them are allowed. When multiple lines form a paragraph, all inline styles can span over multiple lines.

Inline style examples
Unformatted Formatted
*bold* bold
_italic_ italic
_*bold italic*_ bold italic
``code`` code
*bold*, then _italic_ and finally ``some code`` bold, then italic and finally some code
This is *bold\n
on multiple\n
lines*.
This is bold
on multiple
lines.

6.4.4   URLs

All strings that look like URLs are automatically converted into clickable links. Additionally, URLs that end with extension .jpg, .jpeg, .png, .gif, .bmp or .svg (case-insensitive) will automatically create images. For example, URLs like http://example.com are turned into links, and http:///host/image.jpg and file:///path/chart.png into images.

The automatic conversion of URLs to links is applied to all the data in logs and reports, but creating images is done only for test suite, test case and keyword documentation, and for test suite metadata.

Note

.svg image support is new in Robot Framework 3.2.

6.4.6   Section titles 6.4.6章节标题

If documentation gets longer, it is often a good idea to split it into sections. It is possible to separate sections with titles using syntax = My Title =, where the number of equal signs denotes the level of the title:
如果文档变得更长,将其分成几个部分通常是一个好主意。可以使用语法= My Title =将章节与标题分开,其中等号的数量表示标题的级别:

= First section =

== Subsection ==

Some text.

== Second subsection ==

More text.

= Second section =

You probably got the idea.

Notice that only three title levels are supported and that spaces between equal signs and the title text are mandatory.
请注意,仅支持三个标题级别,并且等号和标题文本之间必须有空格。

6.4.7   Tables 6.4.7表格

Tables are created using pipe characters with spaces around them as column separators and newlines as row separators. Header cells can be created by surrounding the cell content with equal signs and optional spaces like = Header = or =Header=. Tables cells can also contain links and formatting such as bold and italic:
表格是使用管道字符创建的,管道字符周围的空格作为列分隔符,换行符作为行分隔符。标题单元格可以通过在单元格内容周围使用等号和可选空格(如= Header ==Header=)来创建。表格单元格还可以包含链接和格式,如粗体和斜体:

| =A= |  =B=  | = C =  |
| _1_ | Hello | world! |
| _2_ | Hi    |

The created table always has a thin border and normal text is left-aligned. Text in header cells is bold and centered. Empty cells are automatically added to make rows equally long. For example, the above example would be formatted like this in HTML:
所创建的表格始终具有细边框,并且普通文本左对齐。标题单元格中的文本加粗并居中。系统会自动添加空单元格,使行的长度相等。例如,在HTML中,上述示例的格式如下:

ABC
1Hello 你好world 世界
2Hi 

6.4.8   Lists 6.4.8列表

Lists are created by starting a line with a hyphen and space ('- '). List items can be split into multiple lines by indenting continuing lines with one or more spaces. A line that does not start with '- ' and is not indented ends the list:

Example:
- a list item
- second list item
  is continued

This is outside the list.

The above documentation is formatted like this in HTML:

Example: 范例:

  • a list item 列表项
  • second list item is continued
    继续第二列表项

This is outside the list.
这不在名单上。

6.4.9   Preformatted text 6.4.9预格式化文本

It is possible to embed blocks of preformatted text in the documentation. Preformatted block is created by starting lines with '| ', one space being mandatory after the pipe character except on otherwise empty lines. The starting '| ' sequence will be removed from the resulting HTML, but all other whitespace is preserved.
可以在文档中嵌入预先格式化的文本块。预格式化块是通过以"|',管道字符后必须有一个空格,除非是空行。《开始》|'序列将从生成的HTML中删除,但保留所有其他空白。

In the following documentation, the two middle lines form a preformatted block when converted to HTML:
在下面的文档中,中间的两行在转换为HTML时形成了一个预格式化的块:

Doc before block:
| inside block
|    some   additional whitespace
After block.

The above documentation is formatted like this:
上面的文档格式如下:

Doc before block: 区块前单据:

inside block
  some   additional whitespace

After block. 在街区后面。

6.4.10   Horizontal ruler 6.4.10水平尺

Horizontal rulers (the <hr> tag) make it possible to separate larger sections from each others, and they can be created by having three or more hyphens alone on a line:
水平标尺(<hr>标记)可以将较大的部分彼此分开,并且可以通过在一行上单独使用三个或更多连字符来创建它们:

Some text here.

---

More text...

The above documentation is formatted like this:
上面的文档格式如下:

Some text here. 这里有一些文字。


More text... 更多文本...

6.5   Time format 6.5时间格式

Robot Framework has its own time format that is both flexible to use and easy to understand. It is used by several keywords (for example, BuiltIn keywords Sleep and Wait Until Keyword Succeeds), DateTime library, and timeouts.
Robot Framework有自己的时间格式,使用灵活且易于理解。它由多个关键字(例如,内置关键字SleepWait Until Keyword Succeeds)、DateTime库和超时使用。

6.5.1   Time as number

The time can always be given as a plain number, in which case it is interpreted to be seconds. Both integers and floating point numbers work, and it is possible to use either real numbers or strings containing numerical values.

Note

In some contexts plain numbers can be interpreted otherwise as times. For example, with WHILE loop limit integers denote the maximum iteration count.

6.5.2   Time as time string
6.5.2时间作为时间字符串

Representing the time as a time string means using a format such as 2 minutes 42 seconds, which is normally easier to understand than just having the value as seconds. It is, for example, not so easy to understand how long a time 4200 is in seconds, but 1 hour 10 minutes is clear immediately.

The basic idea of this format is having first a number and then a text specifying what time that number represents. Numbers can be either integers or floating point numbers, the whole format is case and space insensitive, and it is possible to add - prefix to specify negative times. The available time specifiers are:

  • days, day, d
  • hours, hour, h 小时,小时,h
  • minutes, minute, mins, min, m
    分钟,分钟
  • seconds, second, secs, sec, s
    秒,秒
  • milliseconds, millisecond, millis, ms
    毫秒,毫秒,米利斯,毫秒
  • microseconds, microsecond, us, μs
    微秒,微秒,us,μs
  • nanoseconds, nanosecond, ns
    纳秒,纳秒,ns

Examples: 示例如下:

1 min 30 secs
1.5 minutes
90 s
1 day 2 hours 3 minutes 4 seconds 5 milliseconds 6 microseconds 7 nanoseconds
1d 2h 3m 4s 5ms 6μs 7 ns
- 10 seconds

Note 注意

Support for micro and nanoseconds is new in Robot Framework 6.0.
对微秒和纳秒的支持是Robot Framework 6.0中的新功能。

6.5.3   Time as "timer" string
6.5.3时间作为“计时器”字符串

Time can also be given in timer like format hh:mm:ss.mil. In this format both hour and millisecond parts are optional, leading and trailing zeros can be left out when they are not meaningful, and negative times can be represented by adding the - prefix. For example, following timer and time string values are identical:
时间也可以用计时器的格式表示,如hh:mm:ss.mil。在这种格式中,小时和毫秒部分都是可选的,前导零和尾随零在没有意义时可以省略,负时间可以通过添加-前缀来表示。例如,以下计时器和时间字符串值相同:

Timer and time string examples
计时器和时间字符串示例
Timer 定时器 Time string 时间字符串
00:00:01 1 second 1秒
01:02:03 1 hour 2 minutes 3 seconds
1小时2分3秒
1:00:00 1 hour 1小时
100:00:00 100 hours 100小时
00:02 2 seconds 2秒
42:00 42 minutes 42分钟
00:01:02.003 1 minute 2 seconds 3 milliseconds
1分2秒3毫秒
00:01.5 1.5 seconds 1.5秒
-01:02.345 - 1 minute 2 seconds 345 milliseconds
- 1分2秒345毫秒

6.6   Boolean arguments 6.6布尔参数

Many keywords in Robot Framework standard libraries accept arguments that are handled as Boolean values true or false. If such an argument is given as a string, it is considered false if it is an empty string or equal to FALSE, NONE, NO, OFF or 0, case-insensitively. Other strings are considered true unless the keyword documentation explicitly states otherwise, and other argument types are tested using the same rules as in Python.
Robot Framework标准库中的许多关键字接受作为布尔值true或false处理的参数。如果这样一个参数作为字符串给出,如果它是一个空字符串或等于0NONENOOFF0,则认为它是假的,大小写无关。其他字符串被认为是真的,除非关键字文档显式声明,其他参数类型使用与Python相同的规则进行测试。

*** Keywords ***
True examples
    Should Be Equal    ${x}    ${y}    Custom error    values=True         # Strings are generally true.
    Should Be Equal    ${x}    ${y}    Custom error    values=yes          # Same as the above.
    Should Be Equal    ${x}    ${y}    Custom error    values=${TRUE}      # Python `True` is true.
    Should Be Equal    ${x}    ${y}    Custom error    values=${42}        # Numbers other than 0 are true.

False examples
    Should Be Equal    ${x}    ${y}    Custom error    values=False        # String `false` is false.
    Should Be Equal    ${x}    ${y}    Custom error    values=no           # Also string `no` is false.
    Should Be Equal    ${x}    ${y}    Custom error    values=${EMPTY}     # Empty string is false.
    Should Be Equal    ${x}    ${y}    Custom error    values=${FALSE}     # Python `False` is false.
    Should Be Equal    ${x}    ${y}    Custom error    values=no values    # Special false string with this keyword.

Note 注意

Considering OFF and 0 false is new in Robot Framework 3.1.
考虑OFF0false是Robot Framework 3.1中的新功能。

6.7   Evaluating expressions
6.7计算表达式

This appendix explains how expressions are evaluated using Python in different contexts and how variables in expressions are handled.
本附录解释了如何在不同的上下文中使用Python计算表达式以及如何处理表达式中的变量。

6.7.1   Introduction 6.7.1引言

Constructs such as IF/ELSE structures, WHILE loops and inline Python evaluation as well as several BuiltIn keywords accept an expression that is evaluated in Python:
IF/ELSE结构WHILE循环内联Python求值等构造以及几个BuiltIn关键字接受在Python中求值的表达式:

*** Test Cases ***
IF/ELSE
    IF    ${x} > 0
        Log to console   ${x} is positive
    ELSE
        Log to console   ${x} is negative
    END

Inline Python evaluation
    Log to console    ${x} is ${{'positive' if ${x} > 0 else 'negative'}}

Evaluate keyword
    ${type} =    Evaluate    'positive' if ${x} > 0 else 'negative'
    Log to console    ${x} is ${type}

Should Be True keyword
    Should Be True    ${x} > 0

Notice that instead of creating complicated expressions, it is often better to move the logic into a test library. That typically eases maintenance and also enhances execution speed.
请注意,与其创建复杂的表达式,不如将逻辑移到测试库中。这通常会简化维护,并提高执行速度。

6.7.2   Evaluation namespace
6.7.2求值命名空间

Expressions are evaluated using Python's eval function so that normal Python constructs like '${x}' == 'expected', ${x} > 0 and '${x}'.upper() not in ('FAIL', 'BAD') can be used and all builtin functions like len() and int() are available. In addition to that, all unrecognized Python variables are considered to be modules that are automatically imported. It is possible to use all available Python modules, including the standard modules and the installed third party modules.
使用Python的eval函数计算表达式,以便可以使用正常的Python结构,如'${x}'=='expected'${x}> 0'${x}'. upper()not in('FAIL','BAD'),并且可以使用所有内置函数,如len()int()。除此之外,所有无法识别的Python变量都被认为是自动导入的模块。可以使用所有可用的Python模块,包括标准模块和已安装的第三方模块。

The following examples demonstrate using Python builtins as well as modules using the inline Python evaluation syntax, but same expressions would also work with IF/ELSE structures and BuiltIn keywords without the need to use the ${{}} decoration around the expression:
下面的示例演示了如何使用Python内置函数以及使用内联Python求值语法的模块,但相同的表达式也可以使用IF/ELSE结构BuiltIn关键字,而无需在表达式周围使用${{}}装饰:

*** Variables ***
${VAR}           123

*** Test Cases ***
Python syntax
    Should Be True       ${{'${VAR}' == '123'}}
    Should Be True       ${{'${VAR}'.startswith('x') or '${VAR}' in '012345'}}

Python builtins
    Should Be Equal      ${{len('${VAR}')}}        ${3}
    Should Be Equal      ${{int('${VAR}')}}        ${123}

Access modules
    Should Be Equal      ${{os.sep}}               ${/}
    Should Be Equal      ${{round(math.pi, 2)}}    ${3.14}
    Should Start With    ${{robot.__version__}}    4.

A limitation of using modules is that nested modules like rootmod.submod can only be used if the root module automatically imports the submodule. That is not always the case and using such modules is not possible. An concrete example that is relevant in the automation context is the selenium module that is implemented, at least at the time of this writing, so that just importing selenium does not import the selenium.webdriver submodule. Another limitation is that modules cannot be used in the expression part of a list comprehension when using Python 3. A workaround to both of these problems is using the BuiltIn keyword Evaluate that accepts modules to be imported and added to the evaluation namespace as an argument:
使用模块的一个局限性是,只有当根模块自动导入子模块时,才能使用像rootmod.submod这样的嵌套模块。但情况并非总是如此,使用这样的模块是不可能的。在自动化上下文中相关的一个具体示例是selenium模块,该模块至少在撰写本文时已实现,因此仅导入selenium不会导入selenium.webdriver子模块。另一个限制是,在使用Python 3时,不能在列表解析的表达式部分使用模块。解决这两个问题的方法是使用BuiltIn关键字Evaluate,它接受要导入并添加到评估命名空间的模块作为参数:

*** Test Cases ***
Does not work due to nested module structure
    Log    ${{selenium.webdriver.ChromeOptions()}}

Evaluate keyword with nested module
    ${options} =    Evaluate    selenium.webdriver.ChromeOptions()    modules=selenium.webdriver
    Log    ${options}

Does not work due to list comprehension
    Log    ${{[json.loads(item) for item in ('1', '"b"')]}}

Evaluate keyword with list comprehension
    ${items} =    Evaluate    [json.loads(item) for item in ('1', '"b"')]    modules=json
    Log    ${items}

The Evaluate keyword also supports custom evaluation namespaces if further customization is needed. See its documentation in the BuiltIn library for more details.
如果需要进一步自定义,Evaluate关键字还支持自定义计算命名空间。有关详细信息,请参阅BuiltIn库中的文档。

6.7.3   Using variables 6.7.3使用变量

Normal ${variable} syntax
常规${variable}语法

When a variable is used in the expression using the normal ${variable} syntax, its value is replaced before the expression is evaluated. This means that the value used in the expression will be the string representation of the variable value, not the variable value itself. This is not a problem with numbers and other objects that have a string representation that can be evaluated directly. For example, if we have a return code as an integer in variable ${rc}, using something like ${rc} > 0 is fine.
当在使用普通${variable}语法的表达式中使用变量时,在计算表达式之前将替换其值。这意味着表达式中使用的值将是变量值的字符串表示,而不是变量值本身。对于数字和其他具有可以直接计算的字符串表示的对象,这不是问题。例如,如果我们在变量${rc}中有一个作为整数的返回代码,使用类似${rc}> 0的东西就可以了。

With other objects the behavior depends on the string representation. Most importantly, strings must always be quoted either with single or double quotes like '${x}', and if they can contain newlines, they must be triple-quoted like '''${x}'''. Strings containing quotes themselves cause additional problems, but triple-quoting typically handles them. Also the backslash character \ is problematic, but can be handled by using Python's raw-string notation like r'${path}'.
对于其他对象,行为取决于字符串表示。最重要的是,字符串必须始终用单引号或双引号引起来,如'${x}',如果它们可以包含换行符,则必须用三引号引起来,如''${x}''。包含引号的字符串本身会导致其他问题,但三重引号通常可以处理这些问题。另外,反斜杠字符\也有问题,但可以使用Python的原始字符串表示法(如r '${path}')来处理。

*** Test Cases ***
Using normal variable syntax
    Should Be True    ${rc} > 0
    IF    '${status}'.upper() == 'PASS'
        Log    Passed
    END
    IF    'FAIL' in r'''${output}'''
        Log    Output contains FAIL
    END

Special $variable syntax
特殊$变量语法

Quoting strings is not that convenient, but there are cases where replacing the variable with its string representation causes even bigger problems. For example, if the variable value can be either a string or Python None, quoting like '${var}' is needed because otherwise strings do not work, but then None is interpreted to be a string as well. Luckily there is an easy solution to these problems discussed in this section.
引用字符串并不那么方便,但在某些情况下,用字符串表示形式替换变量会导致更大的问题。例如,如果变量值可以是字符串或PythonNone,则需要像'${var}'这样的引号,因为否则字符串不起作用,但随后None也被解释为字符串。幸运的是,本节中讨论的这些问题有一个简单的解决方案。

Actual variables values are available in the evaluation namespace and can be accessed using special variable syntax without the curly braces like $variable. Such variables should never be quoted, not even if they contain strings.
实际变量值在求值命名空间中可用,并且可以使用特殊的变量语法访问,而不需要像$variable这样的花括号。这样的变量永远不应该被引用,即使它们包含字符串。

Compare this these examples with the example in the previous section:
将这些示例与上一节中的示例进行比较:

*** Test Cases ***
Using special variable syntax
    Should Be True    $rc > 0
    IF    $status.upper() == 'PASS'
        Log    Passed
    END
    IF    'FAIL' in $output
        Log    Output contains FAIL
    END

Only possible using special variable syntax
    Should Be True    $example is not None
    Should Be True    len($result) > 1 and $result[1] == 'OK'

Using the $variable syntax slows down expression evaluation a little. This should not typically matter, but should be taken into account if complex expressions are evaluated often and there are strict time constrains. Moving such logic to test libraries is typically a good idea anyway.
使用$variable语法会稍微降低表达式求值的速度。这通常不重要,但如果经常计算复杂表达式并且有严格的时间约束,则应考虑到这一点。将这样的逻辑移到测试库通常是一个好主意。

Note 注意

Due to technical reasons, these special variables are available during evaluation as local variables. That makes them unavailable in non-local scopes such as in the expression part of list comprehensions and inside lambdas.
由于技术原因,这些特殊变量在评估期间可作为局部变量使用。这使得它们在非局部作用域中不可用,比如列表解析的表达式部分和类内。

6.8   Registrations 6.8注册

This appendix lists file extensions, media types, and so on, that are associated with Robot Framework.
本附录列出了与Robot Framework关联的文件扩展名、媒体类型等。

6.8.1   Suite file extensions
6.8.1套件文件扩展名

Suite files with the following extensions are parsed automatically:
具有以下扩展名的套件文件将被自动解析:

.robot
Suite file using the plain text format.
使用纯文本格式的套件文件。
.robot.rst
Suite file using the reStructuredText format.
使用reStructuredText格式的套件文件。
.rbt
Suite file using the JSON format.
使用JSON格式的套件文件。

Using other extensions is possible, but it requires separate configuration.
也可以使用其他扩展,但需要单独配置

6.8.2   Resource file extensions
6.8.2资源文件扩展名

Resource files can use the following extensions:
资源文件可以使用以下扩展名:

.resource
Recommended when using the plain text format.
建议在使用纯文本格式时使用。
.robot, .txt and .tsv
.robot.txt.tsv
Supported with the plain text format for backwards compatibility reasons. .resource is recommended and may be mandated in the future.
出于向后兼容的原因,支持纯文本格式。.资源是建议的,将来可能会得到授权。
.rst and .rest
.rst.rest
Resource file using the reStructuredText format.
使用reStructuredText格式的资源文件。
.rsrc and .json
.rsrc.json
Resource file using the JSON format.
使用JSON格式的资源文件。

6.8.3   Media type 6.8.3介质类型

The media type to use with Robot Framework data is text/robotframework.
与Robot Framework数据一起使用的媒体类型是text/robotframework

6.8.4   Remote server port 6.8.4远程服务器端口

The default remote server port is 8270. The port has been registered by IANA.
默认的远程服务器端口是8270。该端口已由IANA注册