[英]How to pass objects to keywords in robot framework?
我有一个在文件MyClass.py
编写的python类MyClass
:
class MyClass(object):
def __init__(self):
self.myvar = list()
def setvar(self, val):
self.myvar = val
def mymethod(self):
return self.myvar
我在Robot Framework中导入如下:
Library MyClass WITH NAME my_component
我还有一个关键字,它调用传递给它的对象方法:
testing component
[Arguments] ${cmp}
log to console ************* ${cmp}
${result} = ${cmp}.mymethod
我有几个从MyClass
类实例化的对象,每个对象都有不同的属性。 我想使用testing component
关键字来获取他们的属性,而不管对象本身。
当我调用testing component
传递my_component
:
Test Method Call
testing component my_component
我明白了:
No keyword with name '${cmp}.mymethod' found.
如果我在关键字testing component
这种方式调用它:
${result} = call method ${cmp} mymethod
我明白了:
Object 'my_component' does not have method 'mymethod'.
我也试过call method my_component mymethod
进行测试,我又得到了Object 'my_component' does not have method 'mymethod'.
。
但是当我使用${result} = my_component.mymethod
,一切正常。
关于如何调用python对象方法的问题的字面答案是你可以使用扩展变量语法(例如: ${cmp.mymethod()}
或者你可以使用call method
关键字(例如: call method ${cmp} mymethod
)。
例如,robot中的常规标量变量是python字符串对象。 因此,我们可以调用它们的方法,如lower()
和upper()
。 以下测试用例显示了如何使用前面提到的两种机制在字符串上调用这些方法:
*** Variables ***
${message} Hello, world # a python string object
*** Test cases ***
Example
# Example using "Call method" keyword
${lower}= call method ${message} lower
should be equal ${lower} hello, world
# Example using extended variable syntax
${upper}= set variable ${message.upper()}
should be equal ${upper} HELLO, WORLD
您的代码存在的问题是您对my_component
和${cmp}
代表的内容的误解。 它们不是 python对象。 相反,它是机器人框架库的名称 。 尽管在引擎盖下它可能作为对库中定义的类的实例的引用而存在,但是在测试中, my_component
只是库的名称 。
这就是为什么my_component.my_method
工程- my_component
是一个库的名称, my_method
是该库中关键字的名称。 这是标准的机器人框架语法。 请参阅机器人框架用户指南中明确指定关键字 。
如果您希望能够将my_component
作为对象传递,则可以使用run keyword
来运行该库中实现的关键字。
例如,首先使用以下代码创建MyClass.py
:
class MyClass(object):
def mymethod(self):
return "Hello, world"
如果用run keyword
替换call method
,则代码可以正常工作:
*** Keywords ***
testing component
[Arguments] ${cmp}
log to console ************* ${cmp}
${result} = run keyword ${cmp}.mymethod
最后,如果您确实想要传递实际的库对象 ,可以使用内置关键字Get Library Instance来获取实际的库对象,然后可以将其与Call方法一起使用
*** Keywords ***
testing component
[Arguments] ${cmp_name}
${cmp}= Get library instance ${cmp_name}
log to console ************* ${cmp}
${result} = call method ${cmp} mymethod
[return] ${result}
奇怪的是,扩展变量语法在这种情况下不起作用。 我不知道为什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.