请告诉我如何将以下机器人(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.
答案 0 :(得分:4)
您的代码无法正常工作,因为机器人不会查看您的脚本以获取上下文,因此无法了解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')