如何将对象传递给机器人框架中的关键字?

2023-12-20

我有一个 python 课程MyClass写在文件中MyClass.py:

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

I get:

No keyword with name '${cmp}.mymethod' found.

如果我在关键字中这样称呼它testing component:

${result} =    call method     ${cmp}   mymethod

I get:

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() and 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 and ${cmp}代表。他们是not蟒蛇对象。相反,它是name一个机器人框架库。即使在底层,它可能作为对库中定义的类实例的引用而存在,从测试中my_component简单来说就是name图书馆的。

这就是为什么my_component.my_method作品-my_component是图书馆的名称,并且my_method是该库中关键字的名称。这是标准的机器人框架语法。看明确指定关键字 http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#specifying-a-keyword-explicitly在机器人框架用户指南中。

如果你想能够通过my_component就好像它是一个对象一样,您可以使用run keyword运行该库中实现的关键字。

例如,首先创建MyClass.py使用以下代码:

class MyClass(object):
    def mymethod(self):
        return "Hello, world"

如果您替换,您的代码可以工作call method with run keyword:

*** Keywords ***
testing component
    [Arguments]       ${cmp}
    log to console    ************* ${cmp}
    ${result} =       run keyword   ${cmp}.mymethod

最后,如果你真的想通过实际的库objectaround,您可以使用内置关键字获取库实例 http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Get%20Library%20Instance获取实际的库对象,然后您可以使用它调用方式 http://robotframework.org/robotframework/latest/libraries/BuiltIn.html#Call%20Method

*** Keywords ***
testing component
    [Arguments]       ${cmp_name}
    ${cmp}=  Get library instance    ${cmp_name}
    log to console    ************* ${cmp}
    ${result} =       call method    ${cmp}    mymethod
    [return]          ${result}

奇怪的是,扩展变量语法在这种情况下不起作用。我不知道为什么。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将对象传递给机器人框架中的关键字? 的相关文章

随机推荐