App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide How to use for loops in Robot Framework?

How to use for loops in Robot Framework?

By Pawan Kumar, Community Contributor -

Robot Framework is an open-source, Python-based automation framework. It is suitable for test and robotic process automation (RPA). The Robot Framework Foundation supports Robot Framework and is used in software creation by several industry leaders.

  • A for loop is a conditional iterative statement in programming used to check for particular criteria and then repeatedly execute a code block as long as those conditions are fulfilled.
  • The for loop differs from other looping statements in that it includes an explicit loop number or loop variable that allows the loop’s body to know the exact sequencing of each iteration.

What is the Robot Framework?

The Robot Framework is an open-source automation framework in general. It is suitable for test and robotic process automation (RPA). It is an open and adaptable framework that may be used with any other tool to construct strong and adaptable automation systems. It is available for free with no licensing fees.

  • The Robot Framework offers a simple syntax that uses human-readable terms. Its capabilities may be expanded by libraries written in Python, Java, or various other programming languages. 
  • It is surrounded by a large ecosystem of libraries and tools built as different projects. The Selenium library is the most widely used library for web development and UI testing.
  • In a tabular structure, test cases are written in keyword language. You can write test cases using any text editor or Robot Integrated Development Environment (RIDE). 
  • It is compatible with all operating systems. 
  • The framework is written in Python and is supported by Jython (JVM) and IronPython (.NET). 
  • The Robot framework has built-in keywords and keywords from libraries such as the Selenium Library (open browser, shut browser, maximize browser, and so on). 

We may also make user-defined keywords from others or built-in or library keywords. We may also give arguments to those keywords, which turns them into functions that can be reused. Robot does not handle if-else and nested loops, which are essential as the code becomes sophisticated.

What is the purpose of For loops in Robot Framework?

The for loop Robot framework is to automate repetitive tasks, reduce manual effort, and make test scripts more efficient and maintainable.

For loops in Robot Framework can be used in various scenarios, such as iterating over a list of test data values to run the same test case with different input parameters or iterating over a set of UI elements to perform the same action on each element.

Key factors for using For loop in Robot Framework:-

  • For loops are used to iterate over a sequence of values or items in Robot Framework.
  • For loops can be nested, allowing multiple levels of iteration.
  • For loops are commonly used in Robot Framework to automate repetitive tasks, such as iterating over a list of test data or UI elements.
  • By using For loops, test scripts can be made more efficient, maintainable, and less prone to errors.
  • For loops can also be used with conditional statements, allowing for more complex control flow in test scripts.
  • For loops can also be used with user-defined keywords to perform a sequence of actions for each item.
  • The Continue For Loop If and Exit For Loop If keywords can be used to control the flow of a for loop based on a condition.
  • For loops can be used to iterate over a sequence of files or directories, allowing for file operations or data processing.
  • The ELSE statement can be used in a for loop to execute actions if the loop completes without interruption.
  • Loops can generate and verify test data or create dynamic test cases based on input parameters.

How to write a for loop in Robot Framework?

A FOR loop in Robot Framework is a control structure that allows us to repeat a set of actions a certain number of times, or to iterate over a list or range of values. 

The basic syntax of a robot framework for loop example is as follows:

*** Variables ***
@{list} item1 item2 item3

*** Test Cases ***
Example Test
FOR ${item} IN @{list}
Log ${item}
# Perform other actions on ${item}
END
  • In this example, the FOR loop statement is used to iterate over the @{list} variable. 
  • Within the loop, the ${item} variable is set to each item in the list and printed using the Log keyword. 
  • We can replace the “log” keyword with any other keyword to perform different actions on each item in the list. 

We can also use Python’s built-in range function to iterate a specific number of times. Here is an example:

*** Test Cases ***
Example Test
FOR ${i} IN RANGE 5
Log ${i}
END
  • In this example, the FOR loop statement is used with the RANGE keyword to iterate five times, and the ${i} variable is set to the index of each iteration. 
  • The Log keyword is used to print the index of each iteration. 
  • You can replace the Log keyword with any other keyword to perform different actions within the loop.

Basic Syntax of For Loops in the Robot Framework

Robot framework for loop is used to repeat a set of steps a certain number of times or for a specific range of values.

The basic syntax for a for loop robot framework is as follows:

FOR ${index} IN RANGE ${start} ${end} [${step}]
[Keyword or Steps]
[Keyword or Steps]
[Keyword or Steps]
  • ${index}: A user-defined variable to store the current value of the loop iteration.
  • IN RANGE: A keyword used to specify the range of values for the loop.
  • ${start}: The starting value of the range.
  • ${end}: The ending value of the range.
  • ${step} (optional): The increment between each loop iteration. The default is 1.

With the flexibility of the FOR loop syntax, we can customize the loop to fit your specific use case.

  • Data-driven testing: For loops can be used to iterate through a set of test data and execute the same test steps with different data sets. 

For example, if we have a list of usernames and passwords to test login functionality, we can use a for loop to iterate through the list and execute the login test with each set of credentials.

FOR ${user} ${password} IN ZIP @{usernames} @{passwords}
Input Text ${username_field} ${user}
Input Text ${password_field} ${password}
Click Button ${login_button}
Wait Until Page Contains ${welcome_message}
Click Button ${logout_button}

Processing lists or tables: It can process a list or table of data and perform the same actions on each item in the list or table.

For example, if we have a list of products and their prices, we can use a for loop to calculate the total cost of all the products.

FOR ${product} ${price} IN ZIP @{products} @{prices}
${subtotal} = Evaluate ${price} * ${quantity}
${total} += ${subtotal}
  • Generating test data: It can be used to generate test data and execute test cases with the generated data. 

For example, if a test case requires a unique email address each time it is executed, we can use a for loop to generate a list of unique email addresses and execute the test case with each email address.

FOR ${i} IN RANGE 1 ${number_of_tests}
${email} = Generate Unique Email
Run Keyword And Continue On Failure Submit Registration Form ${email} ${password}
  • Repeating actions a fixed number of times: It can be used to repeat a set of actions a fixed number of times. For example, if we need to execute a set of test steps 10 times to test stability and performance, we can use a for loop to repeat the set of steps 10 times.
FOR ${i} IN RANGE 1 10
Click Button ${random_button}
Wait Until Page Contains Element ${random_element}
Click Button ${back_button}

These are just a few examples of the many ways for loops can be used in Robot Framework for real-time use cases. The versatility of the for loop syntax allows us to apply them in a wide range of testing scenarios.

Using For Loops with Lists in the Robot Framework

In the Robot Framework, we can use for loops with lists using the built-in FOR loop construct in combination with Python code. Here’s an example of how to do this:

Define your list in a test case or keyword: 

*** Test Cases ***
Example Test Case
${my_list}= Create List item1 item2 item3
FOR ${item} IN @{my_list}
Log ${item}
END

In the above example, the Create List keyword creates a list with items item1, item2, and item3. The FOR loop then iterates through each item in the list and logs the item to the console.

We  can also use Python code within the FOR loop to manipulate the list items:

*** Test Cases ***
Example Test Case
${my_list}= Create List item1 item2 item3
FOR ${item} IN @{my_list}
Log ${item}
END
  • In the above example, the Create List keyword creates a list with three items: 1, 2, and 3.
  • The FOR loop then iterates through each item in the list using the RANGE keyword, which generates a range of values from 0 to the length of the list. 
  • The Python code within the loop multiplies each item by 2, effectively doubling its value. Finally, the Log List keyword logs the modified list to the console.

Note that the ${} syntax is used to access variables in Robot Framework. In the Python code within the FOR loop, the ${index} variable is used to access the current index of the list, and the ${my_list[${index}]} syntax is used to access the value of the list item at the current index.

Using For Loops with Dictionaries in Robot Framework 

With Robot Framework, we  can use the built-in FOR loop construct in combination with Python code for loops with dictionaries. Here’s an example of how to do this:

Define your dictionary in a test case or keyword:

*** Test Cases ***
Example Test Case
${my_dict}= Create Dictionary key1=value1 key2=value2 key3=value3
FOR ${key} IN @{my_dict.keys()}
${value}= Set Variable ${my_dict[${key}]}
Log Key: ${key} Value: ${value}
END
  • In the above example, the Create Dictionary keyword creates a dictionary with three key-value pairs. 
  • The FOR loop then iterates through each key in the dictionary using the keys() method and sets the corresponding value to a variable using the ${my_dict[${key}]} syntax. 
  • The Log keyword then logs both the key and value to the console.

We  can also use Python code within the FOR loop to manipulate the dictionary items:

*** Test Cases ***
Example Test Case
${my_dict}= Create Dictionary key1=1 key2=2 key3=3
FOR ${key} IN @{my_dict.keys()}
${my_dict[${key}]}= Set Variable ${my_dict[${key}]} * 2
END
Log Dictionary ${my_dict}
  • In the above example, the Create Dictionary keyword creates a dictionary with three key-value pairs. 
  • The FOR loop then iterates through each key in the dictionary using the keys() method. 
  • The Python code within the loop multiplies each value by 2, effectively doubling its value.
  • Finally, the Log Dictionary keyword logs the modified dictionary to the console.

Note that the ${} syntax is used to access variables in Robot Framework. In the Python code within the FOR loop, the ${key} variable is used to access the current key of the dictionary, and the ${my_dict[${key}]} syntax is used to access the value of the dictionary item at the current key.

Nesting For Loops in Robot Framework 

A nested for loop is a loop inside another loop. In programming, it allows you to iterate through multiple lists or items at once by going through the outer loop first, then through the inner loop for each iteration of the outer loop.

We can nest for loops in Robot Framework using the built-in FOR loop construct. Nesting for loops allows us to iterate through multiple lists or items simultaneously. 

Here’s an example of how to do this:

*** Test Cases ***
Example Test Case
@{list1}= Create List 1 2 3
@{list2}= Create List A B C
FOR ${item1} IN @{list1}
Log Outer loop item: ${item1}
FOR ${item2} IN @{list2}
Log Inner loop item: ${item2}
END
END
  • In this example of nest For loop, the Create List keyword is used to create two lists, list1 and list2, each with three items. 
  • The outer FOR loop iterates through each item in list1, and the inner FOR loop iterates through each item in list2
  • The Log keyword is then used to print each item to the console.

When nesting FOR loops, include an END statement for each loop. The inner FOR loop must be closed before the outer FOR loop. You can also use Python code within the loops to perform more complex operations.

*** Test Cases ***
Example Test Case
@{list1}= Create List 1 2 3
@{list2}= Create List A B C
FOR ${item1} IN @{list1}
Log Outer loop item: ${item1}
FOR ${item2} IN @{list2}
${result}= Run Keyword And Return Status Should Contain ${item2} ${item1}
Run Keyword If '${result}' == 'True' Log Inner loop item: ${item2}
END
END
  • Here, the Should Contain keyword checks if ${item2} contains ${item1}
  • The Run Keyword If a keyword is then used to check if the previous keyword returned True. 
  • If so, the Log keyword prints ${item2} to the console. This demonstrates how you can use for loops to perform more complex operations in your test cases.

Controlling the execution of a for loop manually

Controlling the execution of a for loop manually refers to the ability to modify the behavior of a loop using statements or conditions within the loop itself. This allows us to control when the loop executes, terminates and which iterations are skipped or executed.

In programming, there are two main ways to control the execution of a for loop manually: the break and continue statements.

  • The break statement allows us to terminate the loop prematurely based on a condition. When the break statement is executed, the loop immediately stops iterating, and the program continues with the code that follows the loop.
  • The continue statement allows us to skip an iteration of the loop based on a condition. When the continue statement is executed, the loop skips the current iteration and proceeds with the next one.

Using these statements can help us make our code more efficient and concise. For example, suppose we know that a certain condition will never be met in the middle of a loop. In that case, we can use a break statement to terminate the loop prematurely and avoid unnecessary iterations. Similarly, if we need to skip certain iterations of a loop based on a condition, we can use a continue statement to achieve this.

When we are executing a for loop in the robot framework, we can also control the execution of a for loop manually using keywords such as Exit For Loop If and Continue For Loop If. These keywords work similarly to the break and continue statements in Python but are specifically designed for use in Robot Framework test cases.

FOR ${item} IN @{list}
${result}= Run Keyword And Return Status Should Be Equal ${item} foo
Continue For Loop If ${result} # skip iteration if ${item} is equal to "foo"
Log ${item}
Exit For Loop If ${item} == "bar" # terminate loop if ${item} is equal to "bar"

In the above code, the Continue For Loop If keyword skips the iteration of the loop if ${item} is equal to “foo”, and the Exit For Loop If keyword terminates the loop prematurely if ${item} is equal to “bar”.

Best Practices for using For Loops in Robot Framework

When we use the For loop in the robot framework, we must keep the following points in mind:

  • Keep it simple: The most effective use of for loops is when the iteration logic is simple and easy to understand. Complex or convoluted iteration logic can make your code harder to read and debug.
  • Use descriptive variable names: Use variable names that clearly describe what the variable represents. This can make our code more readable and help prevent errors.
  • Limit the scope of variables: It’s generally a good idea to limit the scope of variables used in for loops to the loop itself. This can help prevent naming conflicts and make our code easier to understand.
  • Avoid modifying the list during iteration: Modifying the list being iterated over during the iteration can lead to unexpected behavior and errors. If we need to modify the list, consider creating a copy before iterating.
  • Use the range() function for iterating over indices: When iterating over a list and needing the index of each item, use the range() function. This allows us to iterate over the indices of the list instead of the values themselves.
  • Use built-in keywords whenever possible: Robot Framework provides several built-in keywords for iterating over lists and dictionaries. Whenever possible, use these keywords instead of implementing your iteration logic.
  • Test thoroughly: As with any code, it’s important to test our for loops thoroughly to ensure they are working as expected. Test cases should include edge and negative scenarios to ensure your code is robust and error-free.

Conclusion

For loops are a powerful tool for iterating over lists and dictionaries in the Robot Framework. It allows us to automate repetitive tasks and simplify your code, making it easier to read and maintain. By using for loops effectively and following best practices, we can write more efficient, maintainable, and error-free code in the Robot Framework. 

With Robot framework and Selenium, we can also integrate BrowserStack. To accommodate Selenium capabilities, it internally incorporates Selenium WebDriver functionality. This has created a robust automated website testing tool that must be discussed and used.

Start Testing Now

FAQs 

Is Robot Framework BDD?

  • Robot Framework can be used for Behavior-Driven Development (BDD) testing
  • It supports this approach by using the Gherkin syntax, a standard syntax used in BDD for defining acceptance criteria.
  •  Gherkin syntax consists of keywords such as Given, When, and Then describing a scenario’s steps in natural language.
  • Robot Framework provides a Gherkin-compatible syntax called Robot Framework’s “Given-When-Then” syntax. 
  • This allows test cases to be written in a BDD style using the same keywords and syntax used in Gherkin.

Is Robot Framework better than Selenium?

  • Robot Framework and Selenium are not directly comparable as they serve different purposes in software testing.
  • Robot Framework can utilize Selenium as a test library, leveraging its capabilities for web automation. It’s possible to combine the two and use the strengths of both frameworks together.
  • Selenium is a popular open-source web application testing framework widely used for the automated testing of web applications. It provides rich features for automating web browsers and supports various programming languages such as Java, Python, and Ruby.
  • Robot Framework, on the other hand, is a generic test automation framework that supports a wide range of test automation tasks beyond web application testing. It is designed to be a simple and extensible tool for creating and running automated tests, and it provides a set of built-in libraries and tools for test automation.
Tags
Automation Testing Selenium

Featured Articles

Robot Framework and Selenium Test Automation

Top 8 Python Testing Frameworks in 2023

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.