Call Python from Robot Framework

10,491

Solution 1

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:

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.

Solution 2

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. Here's an example, in a file called CustomLibrary.py located in the same folder as the test:

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. Robot Framework does not directly implement Python, as far as I know, but it is written in 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.

Please note that ExtendedSelenium2Library is exactly the same as Selenium2Library except that it includes code to deal with Angular websites. 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".

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.

Share:
10,491
pythonian
Author by

pythonian

I have been in the Wireless (Wi-Fi) industry for 16 years and in Networking for 25 years, both as an Engineer and as a Leader.

Updated on July 21, 2022

Comments

  • pythonian
    pythonian over 1 year

    I am new to Robot Framework - I have tried to call this code to robot framework, but to no avail. I just need some help in order to run my python script in robot framework and return PASS and FAIL within that application. 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()