在 Python 库中注册机器人框架侦听器

Register Robot Framework listener within Python library

Robot Framework 的 Listener 功能非常适合添加可在命令行上调用的可选 pre/post-processing,例如pybot --listener myListener.py mySuite.robot。但是,我正在为 Robot Framework 创建一个 Python 库,我想自动注册它的侦听器而不需要在命令行上调用,以便在导入我的库时始终使用这些侦听器(我想关键字和听众一起工作)。有没有办法使用 Python 代码注册监听器?

看来我最近没有仔细看文档。这个确切的功能是 Robot Framework 2.8.5 中的新功能:http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-libraries-as-listeners

从机器人框架 2.8.5 开始,您可以将库注册为侦听器。参见 Test Libraries as Listeners in the robot framework user's guide. The original feature request is discussed in issue 811

下面是一个简单的例子。它是一个提供单个关键字 "require test case" 的库。此关键字将另一个测试用例的名称作为参数。该库也是一个监听器,它跟踪哪些测试用例具有 运行。当关键字 运行s 时,它查看已经 运行 测试的列表,如果所需的测试用例还没有 运行 或已经失败,它将失败。

from robot.libraries.BuiltIn import BuiltIn

class DependencyLibrary(object):
    ROBOT_LISTENER_API_VERSION = 2
    ROBOT_LIBRARY_SCOPE = "GLOBAL"

    def __init__(self):
        self.ROBOT_LIBRARY_LISTENER = self
        self.test_status = {}

    def require_test_case(self, name):
        key = name.lower()
        if (key not in self.test_status):
            BuiltIn().fail("required test case can't be found: '%s'" % name)

        if (self.test_status[key] != "PASS"):
            BuiltIn().fail("required test case failed: '%s'" % name)

        return True

    def _end_test(self, name, attrs):
        self.test_status[name.lower()] = attrs["status"]

在测试用例中使用它的示例:

*** Settings ***
| Library | /path/to/DependencyLibrary.py

*** Test Cases ***
| Example of a failing test
| | fail | this test has failed

| Example of a dependent test
| | [Setup] | Require test case | Example of a failing test
| | log | hello, world