Robot Framework中自动失败/不执行的互依赖测试

12 投票
2 回答
11433 浏览
提问于 2025-04-18 15:37

我有很多测试用例,其中有几个测试用例是相互依赖的。请问在执行后面的测试用例时,能不能知道之前执行的测试用例的状态?
在我的情况下,第99个测试用例依赖于一些之前测试用例的状态,因此如果第24个或第38个测试用例失败了,我希望第99个测试用例根本不执行,这样可以节省我很多时间。
如果可以的话,请举个例子说明一下。谢谢!

2 个回答

8

为了解决这个问题,我使用了类似这样的代码:

Run Keyword if  '${PREV TEST STATUS}'=='PASSED'  myKeyword

所以也许这对你来说也会有用。

26

Robot框架非常灵活,而在2.8.5版本中引入的一个新功能让我们可以很容易地编写一个关键字,如果其他测试失败,它就会失败。这个功能就是让一个库充当监听器。通过这个功能,库可以跟踪每个测试的通过或失败状态。有了这些信息,你就可以创建一个关键字,如果某个测试失败,它会立刻失败。

基本的思路是,在每个测试结束时缓存它的通过/失败状态(通过一个特殊的_end_test方法)。然后,利用这个状态来决定是否立即失败。

下面是如何使用这个关键字的一个例子:

*** 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

这里是库的定义:

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"]

撰写回答