机器人框架-获取变量

时间:2020-08-18 16:10:57

标签: python robotframework

我正在尝试使用publicAPI从 report.xml 文件获取变量值。这是报告的样子:

report.xml

它具有变量 Var ,并为其分配了 Test 值。

我已经创建了简单的REST API来运行测试:

from flask import Flask
from flask import request

from robot import run
from robot import run_cli

app = Flask(__name__)

@app.route('/')
def runRobot():
 robotName = request.args.get('robot')
 robotName = robotName + '.robot'
 rc = run(robotName)
 return str(rc)

我想返回 Var 变量的值而不是执行代码。我在documentation中找不到符合我要求的匹配函数

有可能做吗?

1 个答案:

答案 0 :(得分:2)

对于这种情况,我可以想象是一个自定义元数据,您可以使用Set Suite Metadata关键字将其设置为所需的任何值。

然后,您可以创建一个小的ResultVisitor来检索所需的元数据。我在下面的示例中使用Robot Framework 3.1.2。

示例(SO.robot):

*** Test Cases ***
Test
    Set Suite Metadata    My Return Value    My VALUE    append=True    top=True

调用Robot CLI和ResultVisitor的Python文件:

from robot import run_cli
from robot.api import ExecutionResult, ResultVisitor

class ReturnValueFetcher(ResultVisitor):

    def __init__(self):
        self.custom_rc = None

    def visit_suite(self, suite):
        try:
            self.custom_rc = suite.metadata["My Return Value"]
        except KeyError:
            self.custom_rc = 'Undefined' # error, False, exception, log error, etc.
        
        # Only visit the top suite
        return False

# Run robot, exit=False is needed so the script won't be terminated here
rc = run_cli(['SO.robot'], exit=False)

# Instantiate result visitor
retval = ReturnValueFetcher()

# Parse execution result using robot API
# assuming the output.xml is in the same folder as the Python script
result = ExecutionResult("./output.xml")

# Visit the top level suite to retrive needed metadata
result.visit(retval)

# Print return values
print(f"normal rc:{rc} - custom_rc:{retval.custom_rc}")

您的自定义返回值也将在log.html和report.html文件中清晰可见。

enter image description here

这是控制台输出:

enter image description here