2

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()
3
  • Looking for those Robot Framework experts :-) Commented Jun 1, 2017 at 15:21
  • Are you wanting to write a test that calls this code directly (ie: execute python the_script.py), or are you wanting to convert this code to a keyword so that you can write a test which uses the keyword? Commented Jun 1, 2017 at 16:21
  • @BryanOakley - A test that will call my script directly would suffice. Thanks. I've looked at samples online, but can't get a good sense of how it's done properly. Commented Jun 1, 2017 at 16:49

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

8 Comments

I seem to understand the direction you are taking. Let me see if I can get it to work. Thanks a bunch.
Yeah... I don't get it. I just need a sample for the code above. If anyone can help.
@pythonian: what don't you get? You don't understand how to convert your code to a function? Or is it you don't understand how to import functions into a robot test?
I don't understand how to import functions into a robot test. All I really need is a Python Script and an equivalent Robot FrameWork test. Just a working sample is what I need. It doesn't really need to have anything to do with the code supplied above.
@pythonian: correct. robot has really great documentation on how to do this. robotframework.org/robotframework/latest/… About the only thing special about it is the naming convention of having the class be the same name as the file minus the .py suffix.
|
3

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.

Comments

1

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)

In your .py file, simply define a function, for example:

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

And then in your TC file:

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

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

Comments

0

You can download the RobotCode VS Code extension and add this to launch.json:

// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
    {
        "name": "RobotCode: Run Current",
        "type": "robotcode",
        "request": "launch",
        "cwd": "${workspaceFolder}",
        "target": "${file}"
    },
    {
        "name": "RobotCode: Run All",
        "type": "robotcode",
        "request": "launch",
        "cwd": "${workspaceFolder}",
        "target": "."
    },
    {
        "name": "RobotCode: Default",
        "type": "robotcode",
        "request": "launch",
        "purpose": "default",
        "presentation": {
            "hidden": true
        },
        "attachPython": false,
        "pythonConfiguration": "RobotCode: Python"
    },
    {
        "name": "RobotCode: Python",
        "type": "python",
        "request": "attach",
        "presentation": {
            "hidden": true
        },
        "justMyCode": false
    }
]

See https://github.com/d-biehl/robotcode/issues/113

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.