Web store order robot tutorial

Tutorial for creating a software robot for processing Excel-driven web store orders using Robot Framework and RPA Framework.

Swag Labs web store Swag Labs web store

Orders Excel file Orders Excel file

This robot will process web store orders based on the given input Excel file.

The robot uses provided credentials for logging into the store. The credentials are considered sensitive information. The credentials are stored in a vault file in order to not expose them.

Never commit sensitive information in your project. Provide the credentials for your robot from a vault file, environment variables, or with some other mechanism where the credentials are not exposed.

To provide the web store orders for the robot from the Excel file, you are going to implement an order processing library using Python and RPA Framework.

When run, the robot will:

  • open a real web browser and load the web store login page
  • log into the web store using credentials provided using a vault file
  • collect the orders from the provided Excel file using a custom Python library
  • loop through the orders and complete the checkout for each order
  • write log and report files
  • close the browser on process completion

You can find the code for this tutorial at the example activities repository.

We have used this scenario as an example when explaining how to create a Process Definition Document for your RPA projects. Check it out!

Prerequisites

Set up your development environment.

Initialize the software robot directory

Navigate to your projects directory in the terminal or the command prompt. Initialize the software robot directory:

robo init web-store-order-processor

Navigate to the directory:

cd web-store-order-processor

Robot task file

Paste the following Robot Framework code in the tasks/robot.robot file:

*** Settings ***
Documentation     Swag order robot. Places orders at https://www.saucedemo.com/
...               by processing a spreadsheet of orders and ordering the
...               specified products using browser automation. Uses a vault
...               file for credentials.
Resource          keywords.robot

*** Tasks ***
Place orders
    Process orders

Robot keywords file

Paste the following Robot Framework code in the resources/keywords.robot file:

*** Settings ***
Library           OperatingSystem
Library           Orders
Library           RPA.Browser
Variables         variables.py

*** Keywords ***
Process orders
    Validate prerequisites
    Open Swag Labs
    Wait Until Keyword Succeeds    3x    1s    Login    ${SWAG_LABS_USER_NAME}    ${SWAG_LABS_PASSWORD}
    ${orders}=    Collect orders
    FOR    ${order}    IN    @{orders}
        Run Keyword And Continue On Failure    Process order    ${order}
    END
    [Teardown]    Close Browser

Validate prerequisites
    File Should Exist    ${EXCEL_FILE_PATH}
    Variable Should Exist    ${SWAG_LABS_USER_NAME}
    Should Not Be Empty    ${SWAG_LABS_USER_NAME}
    Variable Should Exist    ${SWAG_LABS_PASSWORD}
    Should Not Be Empty    ${SWAG_LABS_PASSWORD}

Open Swag Labs
    Open Available Browser    ${SWAG_LABS_URL}

Login
    [Arguments]    ${user_name}    ${password}
    Input Text    user-name    ${user_name}
    Input Password    password    ${password}
    Submit Form
    Assert logged in

Assert logged in
    Wait Until Page Contains Element    inventory_container
    Location Should Be    ${SWAG_LABS_URL}/inventory.html

Collect orders
    ${orders}=    Get orders    ${EXCEL_FILE_PATH}
    [Return]    ${orders}

Process order
    [Arguments]    ${order}
    Reset application state
    Open products page
    Assert cart is empty
    Wait Until Keyword Succeeds    3x    1s    Add product to cart    ${order}
    Wait Until Keyword Succeeds    3x    1s    Open cart
    Assert one product in cart    ${order}
    Checkout    ${order}
    Open products page

Reset application state
    Click Button    css:.bm-burger-button button
    Wait Until Element Is Visible    id:reset_sidebar_link
    Click Link    reset_sidebar_link

Open products page
    Go To    ${SWAG_LABS_URL}/inventory.html

Assert cart is empty
    Element Text Should Be    css:.shopping_cart_link    ${EMPTY}
    Page Should Not Contain Element    css:.shopping_cart_badge

Add product to cart
    [Arguments]    ${order}
    ${product_name}=    Set Variable    ${order["item"]}
    ${locator}=    Set Variable    xpath://div[@class="inventory_item" and descendant::div[contains(text(), "${product_name}")]]
    ${product}=    Get WebElement    ${locator}
    ${add_to_cart_button}=    Set Variable    ${product.find_element_by_class_name("btn_primary")}
    Click Button    ${add_to_cart_button}
    Assert items in cart    1

Assert items in cart
    [Arguments]    ${quantity}
    Element Text Should Be    css:.shopping_cart_badge    ${quantity}

Open cart
    Click Link    css:.shopping_cart_link
    Assert cart page

Assert cart page
    Wait Until Page Contains Element    cart_contents_container
    Location Should Be    ${SWAG_LABS_URL}/cart.html

Assert one product in cart
    [Arguments]    ${order}
    Element Text Should Be    css:.cart_quantity    1
    Element Text Should Be    css:.inventory_item_name    ${order["item"]}

Checkout
    [Arguments]    ${order}
    Click Link    css:.checkout_button
    Assert checkout information page
    Input Text    first-name    ${order["first_name"]}
    Input Text    last-name    ${order["last_name"]}
    Input Text    postal-code    ${order["zip"]}
    Submit Form
    Assert checkout confirmation page
    Wait Until Page Contains Element    css:.btn_action
    Click Link    css:.btn_action
    Assert checkout complete page

Assert checkout information page
    Wait Until Page Contains Element    checkout_info_container
    Location Should Be    ${SWAG_LABS_URL}/checkout-step-one.html

Assert checkout confirmation page
    Wait Until Page Contains Element    checkout_summary_container
    Location Should Be    ${SWAG_LABS_URL}/checkout-step-two.html

Assert checkout complete page
    Wait Until Page Contains Element    checkout_complete_container
    Location Should Be    ${SWAG_LABS_URL}/checkout-complete.html

Variables file

Paste the following Python code in the variables/variables.py file:

from RPA.Robocloud.Secrets import Secrets

EXCEL_FILE_PATH = __file__ + "/../../devdata/Data.xlsx"
SWAG_LABS_URL = "https://www.saucedemo.com"

secrets = Secrets()
SWAG_LABS_USER_NAME = secrets.get_secret("swaglabs")["username"]
SWAG_LABS_PASSWORD = secrets.get_secret("swaglabs")["password"]

Order processing library

To read in an Excel file and to transform the Excel data to orders for the robot, you are going to implement a custom order collecting library using Python and RPA Framework libraries.

Inside the libraries directory, create a file by name Orders.py and paste in the following code:

from RPA.Excel.Files import Files
from RPA.Tables import Tables


class Orders:
    def get_orders(self, excel):
        files = Files()
        workbook = files.open_workbook(excel)
        rows = workbook.read_worksheet(header=True)

        tables = Tables()
        table = tables.create_table(rows)
        tables.filter_empty_rows(table)

        orders = []
        for row in table:
            first_name, last_name = row["Name"].split()
            order = {
                "item": row["Item"],
                "zip": int(row["Zip"]),
                "first_name": first_name,
                "last_name": last_name
            }
            orders.append(order)

        return orders

Excel file

The order information is stored in an Excel file (Data.xlsx). The file is formatted as follows:

NameItemZip
Sol HeatonSauce Labs Bolt T-Shirt3695
Gregg ArroyoSauce Labs Onesie4418
Zayaan HurleySauce Labs Bolt T-Shirt3013
Tyler-James HaighTest.allTheThings() T-Shirt (Red)4403
Camden MartinSauce Labs Bolt T-Shirt1196
Zoya RocheSauce Labs Fleece Jacket3127
Aasiyah AvilaSauce Labs Onesie3238
Nur MaganaSauce Labs Bolt T-Shirt2145
Neil ParkinsonTest.allTheThings() T-Shirt (Red)2401
Vinay GoodwinSauce Labs Fleece Jacket3061

Download the Excel file and save it in the devdata directory.

Credential vault file

The robot reads the credentials from a vault file.

Create a vault.json on your file system. Place the file outside your repository, for example, /tmp/vault.json. Do not commit your vault file.

Paste this content in the vault file:

{
  "swaglabs": {
    "username": "standard_user",
    "password": "secret_sauce"
  }
}

Configure file vault support

Paste the following in devdata/env.json:

{
  "RPA_SECRET_MANAGER": "RPA.Robocloud.Secrets.FileSecrets",
  "RPA_SECRET_FILE": "/tmp/vault.json"
}

Edit the RPA_SECRET_FILE variable to point to the vault.json file on your filesystem. On macOS / Linux, use normal file paths, for example, /tmp/vault.json. On Windows 10, you need to escape the path, for example, C:\\Users\\User\\vault.json.

Wrap the robot

robo wrap

Run the robot

Note that we are using the -v command option, pointing to the file containing our environment variables.

Windows:

robo run entrypoint.cmd -v devdata\env.json

macOS / Linux:

robo run entrypoint.sh -v devdata/env.json

Summary

You executed an order processing robot. Congratulations!

During the process, you learned some concepts and features of the Robot Framework and the RPA Framework:

  • Using a vault file for sensitive data (vault.json)
  • Validating task prerequisites (File Should Exist, Variable Should Exist)
  • Asserting task state (Assert logged in, Assert item in cart...)
  • Resetting task state for the next item (Reset application state)
  • Retrying keywords n times with a given delay (Wait Until Keyword Succeeds)
  • Implementing a custom library (Orders.py)
  • Using a third-party library in your own library (from RPA.Excel.Files import Files)
  • Reading Excel files and transforming to business entities (orders)
  • Creating an executable package (robo wrap)
  • Running robot files, providing environment variables as a file (robo run entrypoint.sh -v devdata/env.json, robo run entrypoint.cmd -v devdata\env.json)
  • Organizing your project files in subdirectories (robo init web-store-order-processor)