Python 机器人框架:如何将机器人的 txt 代码转换为 Python 代码

Python Robot Framework : How to convert robot's txt code into Python code

请告诉我如何将以下机器人 (txt) 代码转换为 Python 代码。机器人代码。

*** Settings ***
Library     OperatingSystem
*** Keywords ***
nik_key_1
    [Arguments]           ${arg1_str}
    log to console      ${arg1_str}
*** Variables ***
${var1}         "variable1"
*** Test Cases ***
First Test Case
    ${output}=   run     "hostname"
    log to console      ${output}
    ${str1}=    catenate    "nikhil"    "gupta"
    nik_key_1               "NikArg1"
    log to console      ${var1}
    log to console      ${str1}

以下是我试过的代码:

from robot.api import TestSuite
from robot.running.model import Keyword
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword
bi = BuiltIn()

@keyword(name='nik_key_1')
def nik_key_1(username):
    bi.log_to_console(message=username,stream='STDOUT',no_newline=False)

suite = TestSuite('Activate Skynet')
suite.resource.imports.library("OperatingSystem")
keyword1 = Keyword(name="nik_key_1",type='kw',doc="nik_key_doc1",args=
["nikusername"])
suite.keywords.append(keyword1)
test = suite.tests.create(name='nik_test_case1', tags=['smoke'])
test.doc = "nik doc"
print dir(test.keywords)
test.keywords.create('nik_key_1', args=['nikusername'],type='kw')

result = suite.run(critical='smoke', output='skynet.xml')

以下是我遇到的错误:

No keyword with name 'nik_key_1' found.   

您的代码不起作用,因为机器人不会查看您的脚本的上下文,因此不知道 nik_key_1。由于您的套件没有导入此脚本,因此它无法访问任何功能。您需要将 nik_key_1 移动到一个文件,然后将该文件导入到套件中。

例如,创建一个名为keywords.py的文件,并在其中放入:

# keywords.py
from robot.api.deco import keyword
from robot.libraries.BuiltIn import BuiltIn

bi = BuiltIn()

@keyword(name='nik_key_1')
def nik_key_1(username):
    bi.log_to_console(message=username,stream='STDOUT',no_newline=False)

接下来,修改您的测试以包含此库:

suite.resource.imports.library('keywords.py')

然后您可以从测试中调用关键字。

将您的脚本用作库

可以将您的脚本和关键字合并到一个文件中,但这涉及通过在导入文件时保护可执行代码免受 运行 使您的脚本可导入。

例如,您可以将脚本重写为如下所示。请注意脚本的可执行部分如何位于测试文件是否已导入的块内。另请注意,脚本本身作为库添加 (suite.resource.imports.library(__file__))

from robot.api import TestSuite
from robot.running.model import Keyword
from robot.libraries.BuiltIn import BuiltIn
from robot.api.deco import keyword

bi = BuiltIn()

@keyword(name='nik_key_1')
def nik_key_1(username):
    bi.log_to_console(message=username,stream='STDOUT',no_newline=False)

if __name__ == "__main__":
   suite = TestSuite('Activate Skynet')
   suite.resource.imports.library('OperatingSystem')
   suite.resource.imports.library(__file__)
   test = suite.tests.create('Should Activate Skynet', tags=['smoke'])
   test.keywords.create('Set Environment Variable', args=['SKYNET', 'activated'], type='setup')
   test.keywords.create('Environment Variable Should Be Set', args=['SKYNET'])
   test.keywords.create('nik_key_1', args=['nikusername'],type='kw')
   result = suite.run(critical='smoke', output='skynet.xml')