Skip to main content
 首页 » 编程设计

python之Robot Framework之将库函数作为参数传递

2024年10月25日8zhengyun_ustc

我有一个简单的测试用例,但无法在我的 testLib.py 中运行。我有:

def free(arg): 
  print "found arg \"{0}\"".format(arg) 
 
 
class testLib: 
 
  def free_run(self,func,arg): 
    print "this is free test" 
    func(arg) 
 
  def member_func(self,arg): 
    print "mem func arg={0}".format(arg) 
 
if __name__ == "__main__": 
  x = testLib(); 
  x.free_run(free,"hello world") 
  x.free_run(x.member_func,"free - mem test") 

然后在 Robot Framework 测试文件 mytest.robot 中我有:

*** Setting *** 
Library         MainLib.py   
Library         testLib.py 
 
*** Test Cases *** 
 
test2 
  free run       free           "testing free run" 
  self run       member_func    "testing self run" 

当我运行框架时,我得到:

============================================================================== 
test2                                                                 | FAIL | 
TypeError: 'unicode' object is not callable 

知道如何将成员函数和自由函数传递给库吗?

请您参考如下方法:

机器人没有任何内置功能是您可以做的。从机器人的角度来看,“免费”只是一个字符串。您需要将其转换为实际的函数对象。我可以想到几种不同的方法来做到这一点。

如果 free 是关键字,您可以这样定义 free_run:

from robot.libraries.BuiltIn import BuiltIn 
def free_run(self,func,arg): 
  print "this is free test" 
  BuiltIn().run_keyword(func, arg) 

另一种选择是在 globals() 返回的结果中查找函数名称,如果可以安全地假设 func 指的是一个全局函数:

def free_run(self,func_name,arg): 
    print "this is free test" 
    func = globals()[func_name] 
    func(arg)