python - 使用动态库的机器人框架自定义关键字中的 run_keyword 方法中的实现问题

标签 python robotframework

我正在使用Python学习机器人框架中的动态库实现。在此过程中,我使用动态库创建了一个新关键字,如 this 中所述。链接。

源码如下

import logging


class libdynamicsampl1:
    def get_keyword_names(self):
        return ["methOne", "methTwo"]

    def methOne(self):
        logging.info("called the methone")

    def methTwo(self, name):
        logging.info("called the methtwo with the arg as" + name)

    def run_keyword(self, name, args):
        print "Running keyword '%s' with arguments %s." % (name, args)
        methArgs = (self,) + (args)
        return getattr(self, name, methArgs)()

当我从机器人文件运行此关键字时,如下面给出的代码,

*** Test Cases ***
Log Dynamic Test Library
    Invoke dyn tests no arg
    Invoke dyn tests with arg

*** Keywords ***
Invoke dyn tests no arg
    meth one

Invoke dyn tests with arg
    meth two    "welcome to awesome robot framework"

出现如下错误,推断是 methTwo 采用“self”和“name”,但使用 getattr(...) 只传递我猜测的名称。

TypeError: methTwo() takes exactly 2 arguments (1 given)

请帮助解决此问题或建议有关如何根据输入参数调用方法的最佳实践/实现。机器人框架站点没有示例,因此任何修复都会非常有帮助。

run_keyword 方法中的以下实现工作正常,但我认为这不是在生产就绪代码库中实现的最佳实践。

def run_keyword(self, name, args):
    print "Running keyword '%s' with arguments %s." % (name, args)
    if name == "methOne":
        return self.methOne()
    if name == "methTwo":
        return self.methTwo(args[0])

最佳答案

using getattr(...) passes only the name I guess.

这取决于您如何定义“仅名称”。 getattr 将返回函数,它对函数参数一无所知。但是,它返回的函数将是对象上的方法,因此您不必担心传递 self 参数。

考虑这段代码:

return getattr(self, name, methArgs)()

与此代码相同(假设name是有效的方法名称)

func = getattr(self, name, methArgs)
func()

假设目前 getAttr 返回 self.methTwo,上面的代码与此相同:

self.methTwo()

请注意,在上面,您的代码没有传递任何参数。当在 getattr 中使用时,该变量不代表参数,它代表一个默认方法名称,以防所请求的方法不存在。换句话说,当name有效时,getattr将简单地忽略methArgs

由于您的方法之一需要一个参数 (name ),因此您将收到一个错误,表明它没有收到所需的所有参数。显然,这正是发生的事情。

您的示例还存在其他问题,因此我无法确定确切的解决方案。目前尚不清楚您是否期望测试中的 meth one 调用 methOne,或者 meth onemethOne 是一个错字。

假设您在两个地方都使用了正确的名称,您可以直接使用 getattr 将名称转换为方法,类似于您现在的做法。区别只是您需要将参数传递给函数而不是 getattr

例如,给定这个机器人代码片段:

Invoke dyn tests with arg
    methTwo    "welcome to awesome robot framework"

以下是如何实现 run_keyword 以使机器人代码运行:

def run_keyword(self, name, args):
    print "Running keyword '%s' with arguments %s." % (name, args)
    func = getattr(self, name)
    return func(*args)

关于python - 使用动态库的机器人框架自定义关键字中的 run_keyword 方法中的实现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55242514/

相关文章:

python - 如何将 bool 变量从机器人框架传递给 python 函数

python - 如何在python中解密密码

python - 如何在Python中存储二维数组,就像MySQL中的表一样?

python-2.7 - 如何使用python检查机器人框架中的字典是否为空

Robotframework 获取重复迭代

python - 如何从嵌套字典中获取值?

python - Django urls.py 系统可以变成 Pylon 的路由吗?

python - Mesos/src/examples/python/test_framework.py 第 25 行,找不到 mesos.native

python - 我正在尝试获取当前在 Windows 7 上使用 Python 运行的所有进程和应用程序

python - 如何在机器人框架中动态导入变量文件