Robot framework Usage Summary


Recently, the open source automated testing framework robot framework has been used in the project. To sum up, I hope it will be helpful to you.


First, make sure that Python is installed on the system. Then you can install using PIP:
pip install robotframework
After installation, use the following command to view the version:
robot –version
Then we can create a simple test script:

*** Settings ***
Documentation     Example using the space separated format.
Library           OperatingSystem

*** Variables ***
${MESSAGE}        Hello, world!

*** Test Cases ***
My Test
    [Documentation]    Example test.
    Log    ${MESSAGE}
    My Keyword    ${CURDIR}

Another Test
    Should Be Equal    ${MESSAGE}    Hello, world!

*** Keywords ***
My Keyword
    [Arguments]    ${path}
    Directory Should Exist    ${path}

You can then run the test script using the robot:
robot helloworld.robot
The operation results are as follows:

You can also install and use ide tool ride, which can be used to easily create automatic test projects and write test scripts. PIP makes it easy to install:

pip install robotframework-ride

String operation

Robot framework string splicing needs to use the cate keyword. The following code combines hello and world

${s}=  catenate   Hello  World

The result is hello world. If we want no space in the middle, we need to use the separator parameter:

${s}=  catenate    SEPARATOR=   Hello   World

The result is HelloWorld. The separator parameter declares the concatenation characters in the splicing. The output result of the following code is hello|world:

${s}=  catenate    SEPARATOR=|   Hello   World

If the string contains special characters, such as # etc., escape is required. Examples are as follows:

${k}=    catenate    SEPARATOR=    \#val_    ${key}    \#

Use the split string keyword in the string library to separate strings. For example, V1, V2 and V3 are separated by commas. The processed results are saved in the list. Examples of use are as follows:

FOR    ${str}    IN    @{dic}
        ${ss}=    String.Split String    ${str}    :
        Set To Dictionary    ${data}    ${ss}[0]    ${ss}[1]

In this example, the keys and values of the incoming parameters are separated by colons, for example:
Name:Jone Age:13
Here, split string is used to separate the key and value and save them in the dictionary.

Note that using the split string keyword requires a reference to the string library.

Test web API

Using the requestslibrary of the robot framework can easily test web APIs. First, you need to install requestlibrary:
pip install robotframework-requests
Then you can write the test script.
First, you need to declare the use of Library:

*** Settings ***
Library    RequestsLibrary

Next, define the access address:

*** Variables ***
${HOST}    http://localhost/myapi

Then you can write use cases:

*** Test Cases ***
API Test Example
	Create Session    my_session    ${HOST}
	${headers}=    Create Dictionary    Accept=application/json    Content-Type=application/json    charset=utf-8

	# POST request with params
	${data}=    Create dictionary    field1=value1    field2=value2
	${response}=    Post Request    my_session    my-endpoint    headers=${headers}    data=${data}

	Should be equal as strings    ${response.status_code}    200
	Log    ${response}

The post method is used here. The key value pairs sent to the API are defined in data. The keyword create dictionary for creating the key value pair dictionary is used here. The returned object is defined in the variable ${response} and can be accessed using post request.

Database related test

During the test, we can directly access the database to check whether the data is correct. At this time, we can use robot framework databaselibrary.

First from After downloading and decompressing, execute Python setup Py install. It can be used after installation.

Create a new test in ride, introduce databaselibrary into library, press F5 to open the search keywords window, and select databaselibrary to list all relevant keywords:

You also need to install a specific database access module. If you access sqlserver, you can install pymssql:

pip install pymssql

Then you can write test cases, such as:

*** Settings ***
Library           DatabaseLibrary

*** Test Cases ***
    Connect To Database Using Custom Params    pymssql    database='dbname',user='username',password='pwd',host='localhost'
    Table Must Exist    AUTH_USER_TB
    Disconnect From Database

There are two keywords in the database library that can be used to connect to the database:
Connect to database and connect to database using custom params. Connect to database needs to declare parameters or save parameters in the configuration file. The parameters are as follows:

dbapiModuleName=None, dbName=None, dbUsername=None, dbPassword=None, dbHost=localhost, dbPort=5432, dbConfigFile=./resources/db.cfg

It should be noted here that if the declaration dbname, dbusername, dbpassword, dbhost or dbport is not displayed, the corresponding configuration items will be found in the specified configuration file. If the configuration file is not found, an error will be reported. The format of the configuration file is as follows:


The following keywords can be used:

  • Check if exists in database: the parameter is a select statement. If there is a query result, it returns true; otherwise, it is false.
  • Check if not exists in database: Contrary to the keyword result above.
  • Delete all rows from table: the parameter is the table name, which deletes all data in the table.
  • Description: the parameter is a select statement, which returns the description array of the query result field, such as name =’id ‘, type_ code=1043, display_ size=None, internal_ size=255, precision=None, scale=None, null_ ok=None)。
  • Execute SQL script: execute SQL script. Multiple SQL statements are separated by semicolons.
  • Query: execute query statements.
  • Row count: returns the number of rows of the query statement.
  • Row count is 0: Returns whether the number of query rows is 0.
  • Row count is equal to X: Returns whether the number of query rows is the given number of rows X.
  • Row Count Is Greater Than X: Returns whether the number of query rows is greater than the given number of rows X.
  • Row Count Is Less Than X: Returns whether the number of query rows is less than the given number of rows X.
  • Table must exist: Specifies whether the table exists.

Custom keywords

Use the robotframework to test the API interface. You need to log in first for each test. In order to reduce repeated login scripts, use the user-defined keywords of the robotframework to simplify the script of the login process. The code is as follows:

*** Keywords ***
Log in to the platform
    [Arguments]    ${host}    ${username}    ${password}
    Create Session    my_session    ${host}
    ${data}=    Create dictionary    UserName=${username}    Password=${password}
    ${response}=    POST On Session    my_session    url=/api/Account/Login    json=${data}
    Log    ${response}
    [Return]    my_session

For convenience, we use Chinese as the keyword name. Then define three input variables, ${host} is the URL to log in, and ${username} and ${password} are the user name and password. Use post on session to log in. After logging in, return to the session created in the login process. For example, this keyword can be used in the test case:

*** Test Cases ***
    ${mysession} = log in to the platform host = ${host} username = saleuser1 password = 1
    ${datalist}=    Create dictionary    WorkFlow_Name=LeaveApply1
    ${responselist}=    POST On Session    ${mysession}    url=${GetActivateListUrl}    json=${datalist}
    Log    ${responselist}

We can save the customized keywords in the resource file, which is convenient for sharing in multiple test cases. The structure of the resource file is basically the same as that of the test file, except that there is no test case, and the variables and user-defined keywords are exactly the same. Reference the resource file in the setting part of the test file, such as:

*** Settings ***
Library           RequestsLibrary
Resource          ../../Resources/flowresources.robot

The location of the resource file is relative to the current path. The path can also contain variables, such as ${resources} / common tsv。
If multiple resource files contain the same user-defined keywords, you need to use the resource file name as a prefix when using these keywords. If multiple resource files contain the same variables, the variables loaded first work.

In many cases, we need to customize the keyword to receive multiple parameters, and the number of parameters is uncertain. In this case, we can declare the parameters as a list and use the @ modifier. The example code is as follows:

    [Arguments]    ${par1}    @{dic}
    Log    ${par1}
    FOR    ${v}    IN    @{dic}
        Log    ${v}

In the above example, ${PAR1} is a fixed parameter, followed by @ {DIC} is a variable parameter list, and the parameters in the list are processed circularly in the user-defined keyword. Examples of calls are as follows:

MultiArgumetns   para1  u1  u2  u3  u4

Develop custom libraries for the robotframework

The robotframework is developed based on python. We use Python to develop custom libraries and provide extensions to the robotframework. Python is very simple to implement, because it doesn’t need any text editor and explanation, and so on. Here, the creation and use process is described by implementing a simple requirement. The requirement is very simple. You need to get the value after flowid = from a string.
First, we create a python file with the following code:

def get_flow_id(url):
    idx = url.index('flowid=')+7
    le = len(url)
    flow_id = url[idx:le]
    return flow_id

Then you can reference this library in the robot file and add the following in settings:

*** Settings ***
Library           ../pylibs/

Here, the location of the library is relative to the location of the current file.
In test cases or keywords, you can use the new keywords defined in the user-defined library. Here, get_ flow_ The new keyword corresponding to ID is get flow ID, “” The symbol is replaced by a space and the following characters become uppercase. The following is an example of using:

${fid}    Get Flow Id    ${rurl}