简体   繁体   中英

How to call a python method from robot framework

I need to call a python method from robot framework.

def getRandomEmails():
    a = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(16))
    email = a + '@' + 'gmail.com'
    return email

This function is written in EnvVar.py file How can I use the returned value from this method in Robot Framework. I have tried almost many ways, but nothing works. please help.

Using Evaluate

Exactly how to do it on your system depends on how your files are organized and how you've configured robot, but in short, Evaluate from the BuiltIn library is the keyword that lets you run arbitrary methods from importable modules.

Example:

For this example I've created a file named EnvVar.py in the current working directory. It has the following contents:

import random, string

def getRandomEmails():
    a = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(16))
    email = a + '@' + 'gmail.com'
    return email

I then created a file named "example.robot" that looks like this:

*** Test cases ***
Example
    ${result}=  evaluate  EnvVar.getRandomEmails()  modules=EnvVar
    log  result: ${result}

Since the current working directory isn't by default on my PYTHONPATH (your setup may be different), I have to tell robot to include the current directory on PYTHONPATH. I can do that with the --pythonpath option.

$ robot --pythonpath . example.robot  

Creating a keyword library

Another solution is to create your own keyword library that exposes this function as a keyword.

For example, assuming you can import EnvVar, you could write a library named "Util" (Util.py) that creates a keyword that calls this function:

# Util.py
import EnvVar

def get_random_emails():
    return EnvVar.getRandomEmails()

You would then use this in a test like any other keyword library:

*** Settings ***
Library  Util.py

*** Test Cases ***
Example
    ${result}=  Get Random Emails
    log  result: ${result}

If it's the only method you want to add than you could add keyword decorator ie:

from robot.api.deco import keyword

@keyword
def getRandomEmails():
    a = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range(16))
    email = a + '@' + 'gmail.com'
    return email

And obviously you should import in settings as library

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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