有没有办法将连接到硬件的对象传递给 Robot Framework?

Is there a way to pass objects connected to hardware to Robot Framework?

我想用 Robot Framework 测试硬件设备。由于我不想在每个测试用例中再次断开和连接我的设备,我想知道是否有可能在 Robot Framework 外部初始化一个 Python 对象但在其中使用。

查看我的代码示例如下:

Main.py:

from robot import run
from SomeLibraryUsedByRobot import SomeLibraryUsedByRobot

device = Device()
SomeLibraryUsedByRobot.device = device

run('SomeRobotFile.robot')

SomeLibraryUsedByRobot.py:

class SomeLibraryUsedByRobot:
    device = None

    def access_device(self):
        device.some_function()

SomeRobotFile.robot:

*** Settings ***
Library             SomeLibraryUsedByRobot.py

*** Test Cases ***  
Some Test
    Access Device

主文件的执行导致错误'NoneType' object has no attribute some_function这让我得出结论,主文件中库的字段device的初始化不起作用。

我还使用机器人框架的侦听器接口及其功能尝试了我的计划library_import(self, name, attributes)

MyListener.py:

class MyListener:
    ROBOT_LISTENER_API_VERSION = 2

    def library_import(self, name, attributes):
        if name == "SomeLibraryUsedByRobot":
            device = Device()
            SomeLibraryUsedByRobot.device = device
            print( "SomeLibraryUsedByRobot initialized with device" )

当我尝试使用监听器时,我直接从控制台执行机器人文件(而不是使用 main.py)。我还在库里面加了一行class:ROBOT_LIBRARY_SCOPE = 'TEST SUITE'.

肯定会调用 library_import(...) 函数,因为我在控制台上看到了打印。但结果与第一次尝试相同:'NoneType' object has no attribute some_function.

基本上,我们不必在此讨论中涉及任何硬件。我只想将一些 python 对象从外部传递给机器人框架使用的库。您看到任何解决方案了吗?

为 open/init 设备和 close/deinit 设备创建关键字 SomeLibraryUsedByRobot

class SomeLibraryUsedByRobot:

    # Called upon library import for more: http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#library-scope
    def __init__(self):
        self.device = None

    def access_device(self):
        self.device.some_function()

    def init_device(self):
        self.device = Device()

    def deinit_device(self):
        self.device.deinit()
        self.device = None

现在要避免在每个测试用例中连接、断开连接,请在 Suite Setup/Suite Teardown 中调用这些关键字。

*** Settings ***
Library           SomeLibraryUsedByRobot
Suite Setup       Init Device
Suite Teardown    Deinit Device

*** Test Cases ***
Case 1
    Access Device

Case 2
    Access Device

Case 3
    Access Device

Case 4
    Access Device

通常应用其他现有库(如 Telnet 或 SeleniumLibrary)中使用的方法,其中有 Open ...Close ... 关键字来管理与浏览器的连接,或者 Telnet 与服务器或硬件的连接等

对于多个设备,您可以使用 robot.utils.connectioncache 来管理多个连接。许多现有的库都在使用它。