简体   繁体   English

从 Robot Framework 调用 Python

[英]Call Python from Robot Framework

I am new to Robot Framework - I have tried to call this code to robot framework, but to no avail.我是 Robot Framework 的新手 - 我试图将此代码称为机器人框架,但无济于事。 I just need some help in order to run my python script in robot framework and return PASS and FAIL within that application.我只是需要一些帮助才能在机器人框架中运行我的 python 脚本并在该应用程序中返回 PASS 和 FAIL。 Any help on this would be greatly appreciated.对此的任何帮助将不胜感激。

# -*- coding: utf-8 -*-
import paramiko
import time,sys
from datetime import datetime
from time import sleep

prompt = "#"

datetime = datetime.now()

ssh_pre = paramiko.SSHClient()
ssh_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_pre.connect("192.168.0.1",22, "admin", "admin")
output=""
ssh = ssh_pre.invoke_shell()
sys.stdout=open("ssh_session_dump.txt","w")

print("Script Start Date and Time: ", '%s/%s/%s' % (datetime.month, datetime.day, datetime.year), '%s:%s:%s' % (datetime.hour, datetime.minute, datetime.second))

model="XV4-17034"

ssh.send("more off\n")
if ssh.recv_ready():
    output = ssh.recv(1000)
ssh.send("show system-info\n")
sleep(5)
output = ssh.recv(5000)

output=output.decode('utf-8')
lines=output.split("\n")

for item in lines:
    if "Model:" in item:
        line=item.split()
        if line[1]==model+',':
            print("Test Case 1.1 - PASS - Model is an " + model)
        else:
            print("Test Case 1.1 - FAIL - Model is not an " + model)

ssh.send( "quit\n" )
ssh.close()

datetime = datetime.now()

print("")
print("Script End Date and Time: ", '%s/%s/%s' % (datetime.month, datetime.day, datetime.year), '%s:%s:%s' % (datetime.hour, datetime.minute, datetime.second))
print("")
sys.stdout.close()

If this were my project, I would convert the code to a function and then create a keyword library that includes that function.如果这是我的项目,我会将代码转换为函数,然后创建一个包含该函数的关键字库。

For example, you could create a file named CustomLibrary.py with a function defined like this:例如,您可以使用如下定义的函数创建一个名为 CustomLibrary.py 的文件:

def verify_model(model):
    prompt = "#"
    datetime = datetime.now()
    ssh_pre = paramiko.SSHClient()
    ...
    for item in lines:
        if "Model:" in item:
            line=item.split()
            if line[1]==model+',':
                return True
            else:
                raise Exception("Model was %s, expected %s" % (line[1], model))
    ...

Then, you could create a robot test like this:然后,您可以创建这样的机器人测试:

*** Settings ***
Library  CustomLibrary

*** Test cases ***
Verify model is Foo
    verify model    foo

Of course, it's a tiny bit more complicated than that.当然,它比这稍微复杂一点。 For example, you would probably need to change the logic in the function to guarantee that you close the connection before returning.例如,您可能需要更改函数中的逻辑以保证在返回之前关闭连接。 Overall, though, that's the general approach: create one or more functions, import them as a library, and then call the functions from a robot test.不过,总的来说,这是通用方法:创建一个或多个函数,将它们作为库导入,然后从机器人测试中调用这些函数。

To call Python code from Robot Framework, you need to use the same syntax as a Robot Framework Library, but once you do, it's very simple.要从 Robot Framework 调用 Python 代码,您需要使用与 Robot Framework Library 相同的语法,但是一旦这样做,它就非常简单。 Here's an example, in a file called CustomLibrary.py located in the same folder as the test:这是一个示例,位于与测试位于同一文件夹中的名为 CustomLibrary.py 的文件中:

from robot.libraries.BuiltIn import BuiltIn
# Do any other imports you want here.

class CustomLibrary(object):
    def __init__(self):
        self.selenium_lib = BuiltIn().get_library_instance('ExtendedSelenium2Library')
        # This is where you initialize any other global variables you might want to use in the code.
        # I import BuiltIn and Extended Selenium2 Library to gain access to their keywords.

    def run_my_code(self):
        # Place the rest of your code here

I've used this a lot in my testing.我在测试中经常使用它。 In order to call it, you need something similar to this:为了调用它,你需要类似的东西:

*** Settings ***
Library     ExtendedSelenium2Library
Library     CustomLibrary

*** Test Cases ***
Test My Code
    Run My Code

This will run whatever code you place in the Python file.这将运行您放置在 Python 文件中的任何代码。 Robot Framework does not directly implement Python, as far as I know, but it is written in Python. Robot Framework 并没有直接实现 Python,据我所知,它是用 Python 编写的。 So, as long as you feed it Python in a form that it can recognize, it'll run it just like any other keyword from BuiltIn or Selenium2Library.因此,只要您以 Python 可以识别的形式提供给它,它就会像来自 BuiltIn 或 Selenium2Library 的任何其他关键字一样运行它。

Please note that ExtendedSelenium2Library is exactly the same as Selenium2Library except that it includes code to deal with Angular websites.请注意,ExtendedSelenium2Library 与 Selenium2Library 完全相同,只是它包含处理 Angular 网站的代码。 Same keywords, so I just use it as a strict upgrade.相同的关键字,所以我只是将其用作严格的升级。 If you want to use the old Selenium2Library, just swap out all instances of the text "ExtendedSelenium2Library" for "Selenium2Library".如果您想使用旧的 Selenium2Library,只需将文本“ExtendedSelenium2Library”的所有实例替换为“Selenium2Library”。

Please note that in order to use any keywords from BuiltIn or ExtendedSelenium2Library you will need to use the syntax BuiltIn().the_keyword_name(arg1, arg2, *args) or selenium_lib().the_keyword_name(arg1, arg2, *args) , respectively.请注意,为了使用来自 BuiltIn 或 ExtendedSelenium2Library 的任何关键字,您需要分别使用语法BuiltIn().the_keyword_name(arg1, arg2, *args)selenium_lib().the_keyword_name(arg1, arg2, *args)

The easiest way is importing a .py file into your testsuite using relative path approach, like ./my_lib.py (assume that your python file is in the same folder with your TC file)最简单的方法是使用相对路径方法将.py文件导入您的测试套件,例如./my_lib.py (假设您的 python 文件与您的 TC 文件在同一文件夹中)

In your .py file, simply define a function, for example:在您的.py文件中,只需定义一个函数,例如:

def get_date(date_string, date_format='%Y-%m-%d'):
    return datetime.strptime(date_string, date_format)

And then in your TC file:然后在您的 TC 文件中:

*** Settings ***
Library     ./my_lib.py

*** Test Cases ***
TEST CASE 1
    Get Date    |     ${some_variable}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM