While loops in Robot Framework
A common need in programming is repeating one or more operations until a condition is met. In Robot Framework and Python, this can be done with a while
loop.
The native
WHILE
loop is supported starting from Robot Framework version 5.
The structure of the while loop
The WHILE
construct starts with WHILE
and ends with END
. WHILE
is followed by a Python statement. The loop is executed as long as the statement evaluates to boolean True
. The body of the loop contains the lines to be executed for each loop iteration.
This is an example of a simple while loop in Robot Framework:
The while loop has a default limit of 10000 iterations to avoid accidental infinite loops. The above example throws an exception when it hits the default limit (10000).
This is effectively the same loop as described above:
Here's an example where the loop limit exception is catched and handled:
You can override the loop limit using the limit
argument:
If you really want to loop infinitely, you can achieve that by setting the limit
argument to NONE
.
Wikipedia - Infinite loop: "In computer programming, an infinite loop (or endless loop) is a sequence of instructions that, as written, will continue endlessly, unless an external intervention occurs ("pull the plug"). It may be intentional."
Loop while condition evaluates to True
The following Robot Framework example demonstrates a while loop that executes as long as the value of the ${x}
variable is less than three. The variable value is incremented at the end of each iteration:
Skip a while loop iteration with CONTINUE
CONTINUE
can be used to skip a loop iteration. The loop will continue with the next iteration:
Exit while loop with BREAK
BREAK
can be used to break out of the loop. It will effectively end the loop:
Simulating a while loop
Robot Framework version 4 does not support while loops directly. However, there are ways to achieve very similar results.
Setting a for loop to repeat a high number of times
Using the FOR .. IN RANGE
syntax, we can set a for loop to repeat for a very high number of times. Then, using the Exit For Loop If
keyword, we can specify the condition that we want to "break" the execution.
In this simple example, our loop will continue until a random value equals to "5":
Using the native Python while
syntax in your custom library
Another possibility, depending on your use case, could be to create a custom library using Python, and use the native Python while loop in you keywords there.
You can then use your keywords in your Robot Framework script, calling them with the Wait Until Keyword Succeeds
keyword.