Search code examples
pythonrobotframework

Trouble running python file as a keyword in Robot Framework


I am trying to run a python file as a keyword in robot framework. However, when I run it, it says the keyword is not found. I have tried multiple variations on the following code with no luck. Both the robot framework and python file are in the same directory. My goal is to determine if a particular string is in the .csv file

Robot Framework file:

*** Settings ***
Library             CheckDataInCSV

*** Test Cases ***
    ${encryption_in_csv}=   CheckDataInCSV.IsDataInCsv  | readings.csv  | C:\\Users\\me\\Downloads
    log   |  ${encryption_in_csv}

Python File CheckDataInCSV.py:

from robot.api.deco import keyword

@keyword("IsDataInCsv")
def IsDataInCsv(text, downloads_path):
    f = open(downloads_path+'readings.csv', 'r')
    file_contents = f.readlines()
    f.close()
    for item in file_contents:
        if text in item:
            return True
        else:
            pass
    return False

I have also tried this without the @keyword header as well as just calling the keyword without the library: IsDataInCsv instead of CheckDataInCSV.IsDataInCsv as well as using a different name for the @keyword and function name.


Solution

  • First, make sure your .robot file syntax is correct. You lost Test Case name in your code example.

    *** Settings ***
    Library             CheckDataInCSV
    
    *** Test Cases ***
    Test Name What You Want
        ${encryption_in_csv}=   CheckDataInCSV.IsDataInCsv  | readings.csv  | C:\\Users\\me\\Downloads
        log   |  ${encryption_in_csv}
    

    Back to your question. According to your code, just add the directory path where CheckDataInCSV.py locate to your PYTHONPATH. Then it works.

    Linux command

    export PYTHONPATH=$PYTHONPATH:/YOUR_PY_FILE_PATH
    

    About keyword Library in *** Setting ***. There are two ways to import custom libraries.

    The first way is like your code. It will search your python file in your PYTHONPATH.

    *** Settings ***
        Library             CheckDataInCSV
    

    The other way is like below library name with .py. It will search the relative position with the .robot file. And also you can use absolute position.

    *** Settings ***
        Library             CheckDataInCSV.py