机器人框架:测试用例无法加载在测试套件的父测试套件文件夹中导入的资源文件中的关键字

问题描述:

我正在使用机器人框架来自动测试一个网站,上图是 RIDE 中的测试结构:

Hi, I am using robot framework to automate testing of a website, and the image above is the structure of test in the RIDE:

  • Test:一个测试套件文件夹,我在这里导入资源文件,在文件夹下的init.robot"
  • Sub1:子测试套件,什么都不导入
  • 测试:一个测试用例

我的问题是:在测试用例test"中,robot无法识别Test"测试套件文件夹中导入的关键字,因为会有更多的子测试套件,如sub2,sub3,我如何导入资源在一个地方?我不想在每个测试套件中都导入资源文件,有没有办法做到这一点?

My problem is: in the test case "test", robot cannot recognize the keyword that imported in the "Test" test suite folder, because there will be more sub test suites, like sub2, sub3, how can I import resource in one place? I don't want to import the resource file in every test suite, is there a way to do that?

您可以链接导入.下面是这样一个链和重用的例子.在这个例子中,我们有一个 resources.robot 导入所有不同的 sub*.robot 文件.这是唯一导入这些文件的文件.

You can chain an imports. Below is an example of such a chain and reuse. In this example we have a single resources.robot that imports all of the different sub*.robot files. This is the only file that imports these.

然后有两个testcases*.robot文件继续导入resources.robot并且能够访问sub*.robot 关键字.

Then there are two testcases*.robot files that proceed to import resources.robot and are able to access the content of the sub*.robot keywords.

resources.robot

*** Settings ***
Resource    ../resources/sub1.robot
Resource    ../resources/sub2.robot
Resource    ../resources/sub1.robot

testcases1.robot

*** Settings ***
Resource    ../resources/resources.robot

*** Test Cases ***
TC
   No Operation

testcases2.robot

*** Settings ***
Resource    ../resources/resources.robot

*** Test Cases ***
TC
   No Operation

正如评论中所讨论的,在 __init__.robot 文件中导入的任何关键字在该文件之外均不可用.这在 初始化文件的机器人框架用户指南部分中有明确描述.

As discussed in the comments, that any keyword imported in the __init__.robot file is not available beyond that file. This is clearly described in the Robot Framework User Guide section on Initialization files.

也就是说,如果不希望将主资源文件包含在每个套件文件中,那么另一种方法是在每个套件的开头使用侦听器加载资源文件.可以在此处找到有关侦听器的文档:文档

That said, if the effort of including the master resource file in each suite file undesirable, then an alternative approach is to load the resource file using a listener at the start of each Suite. The documentation on Listeners can be found here: Docs

一个新的例子:

AddResourceListener.py

from robot.libraries.BuiltIn import BuiltIn

class AddResourceListener(object):
    ROBOT_LISTENER_API_VERSION = 2

    def __init__(self):
        pass

    def start_suite(self, name, attributes):
        BuiltIn().import_resource('${EXECDIR}/resource.robot')

resource.robot

*** Keywords ***
Resource Keyword
    Log    "Keyword Executed from Resource File"

TestCase.robot

*** Test Cases ***
TC
    Resource Keyword

然后使用附加参数 --listener AddResourceListener.py 运行常规机器人命令,无论是否导入,您都可以使用该关键字.

Then run your regular robot command with the additional argument --listener AddResourceListener.py and you'll be able to use the keyword regardless if it's imported or not.