我是Robot Framework的新手。我正在编写自己的库来使用Robot,我想保存类对象。我希望在套件设置中创建并保存一次对象,并在整个测试套件中继续使用相同的对象。有没有办法做到这一点?
Aristalibrary.py
import pyeapi
active_conn = None
class AristaLibrary:
def __init__(self, proto="https", hostname='localhost',
username="admin", passwd="admin", port="443"):
self.hostname = hostname
self.proto = proto
self.port = port
self.username = username
self.passwd = passwd
def connect_to(self, proto, hostname, username, passwd, port):
proto = str(proto)
hostname = str(hostname)
username = str(username)
passwd = str(passwd)
port = str(port)
active_conn = pyeapi.connect(proto, hostname, username, passwd, port)
return active_conn
def enable(self, conn, command):
return conn.execute([command])
def get_active_connection(self):
return active_conn
loginsight_sshlib_demo.txt
*** Setting ***
Library BuiltIn
Library String
Library AristaLibrary
*** Variables ***
${hostname} 192.168.117.20
${username} admin
${password} admin
${port} 80
${proto} http
*** Test Cases ***
Test Aristalibrary
${node}= Connect To ${proto} ${hostname} ${username} ${password} ${port}
LOG ${node} level=DEBUG
Test Persistance of variables
${node}= Get Active Connection
${output}= Enable ${node} show version
LOG ${output} level=DEBUG
*** Keywords ***
Open Connection and Login
Open Connection ${hostname}
Login ${username} ${password}
Write enable
${Output}= Read
Log ${Output} level=INFO
答案 0 :(得分:0)
BuiltIn库有一个名为Set Suite Variable的关键字,可让您设置整个套件的全局变量。您需要做的就是在创建对象后调用它:
${node}= Connect To ${proto} ${hostname} ${username} ${password} ${port}
Set Suite Variable ${node}
从那时起,${node}
将适用于所有测试用例。
如果您不想在测试用例中添加额外步骤,则可以让库从库中调用相同的Set Suite Variable
关键字。例如:
from robot.libraries.BuiltIn import BuiltIn
class AristaLibrary:
...
def connect_to(self, proto, hostname, username, passwd, port):
...
active_conn = pyeapi.connect(proto, hostname, username, passwd, port)
BuiltIn().set_suite_variable("${node}", active_conn)
return active_conn
执行上述操作会在您调用${node}
关键字时设置变量connect_to
。
虽然这是一个有趣的解决方案,但它可能会导致混淆测试用例,因为仅仅通过阅读测试就可以设置${node}
的位置。
有关从python代码调用关键字的更多信息,请参阅机器人框架用户指南中名为Using Robot Framework's internal modules的部分。
答案 1 :(得分:0)
您需要定义库生命周期以匹配测试套件生命周期。
只需在库的开头定义以下内容:
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
例如,
class ExampleLibrary:
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
def __init__(self):
self._counter = 0
def count(self):
self._counter += 1
print self._counter
def clear_counter(self):
self._counter = 0
您在库中定义的每个全局变量都可用于整个测试套件中的库。