pythontest automation

Python for test automation: control flow

Control flow in programming refers to the order in which statements are executed in a program. Python supports various control flow structures, including conditional statements (if, elif, else), exception handling, loops (for, while), and branching statements (break, continue, return).

Conditional statements, such as if, elif, and else, allow us to execute specific blocks of code based on certain conditions. These statements evaluate expressions and execute the corresponding block of code if the condition is true.

Exception handling using the try except finally allows us to execute specific blocks of code when an exception occurs during program execution.

Loops, such as for and while, enable repetitive execution of a block of code. The for loop iterates over a sequence of elements, such as a list or tuple, whil** the while loop executes a block of code as long as a specified condition is true.

Branching statements, like break, continue, and return, provide additional control over the flow of execution within loops and functions. The break statement terminates the loop prematurely, while the continue statement skips the rest of the current iteration and proceeds to the next iteration. The return statement exits a function and optionally returns a value.

if

An if-statement in programming is a control flow statement that allows the execution of a certain block of code based on a condition. It is one of the fundamental constructs used for making decisions in computer programs. The basic syntax for an if-statement in Python looks like this:

x = 10
if x > 5:
    print("hello")

Here the condition is x < 5 (which in this case is True). When the condition is True, the indented code block will be run; i.e. "hello" will be printed out. The condition can be anything that can be evaluated as a boolean. In Python all data types will evaluate to True or False depending on the value.

  • int: 0 evaluates to False, any other number evaluates to True.
  • float: 0.0 evaluates to False, any other number evaluates to True.
  • str: "" (empty string) evaluates to False, any other string evaluates to True.
  • list/tuple/set/dict: Empty lists, tuples, sets and dicts all evaluate to False, lists, tuples, sets and dicts that contain any values evaluate to True.

if-elif

We can add more branches to an if statement using elif:

x = 10
if x < 5:
    print("x is smaller than 5")
elif x > 5:
    print("x is greater than 5")

In this flow, x is greater than 5 is printed because the first condition x < 5 is evaluates to False, and the second condition x > 5 evaluates to True. Note that both of the conditions could evaluate to True, but only the first indented block would be executed. Conditions are evaluated in the same order they are defined.

There can be multiple elif-statements in a single if-elif flow.

if-elif-else

We can add a default branch to an if-statement:

x = 5
if x < 5:
    print("x is smaller than 5")
elif x > 5:
    print("x is greater than 5")
else:
    print("x is 5")

In this flow, neither of the two conditions evaluate to True, therefore the indented block in else is executed, and x is 5 is printed out.

try-except

Exceptions or errors in programming refer to unexpected or exceptional situations that occur during the execution of a program, causing it to behave in an abnormal or erroneous manner. These situations could arise due to various reasons such as incorrect input, hardware failures, network issues, or bugs in the code itself. When an exception occurs, it disrupts the normal flow of the program and may lead to its termination if not properly handled.

In Python we can manage exceptions using try-except:

try:
    print(int("a"))
except ValueError as ex:
    print(ex)

Here we attempt to convert the string "a" into an integer, which raises an exception, a ValueError specifically, when the code is run. With the try-except statement we can catch this exception, and instead of crashing our program, we can do something else; in this case simply print out the exception that occurred. In a real case, try-except can be used to retry an action for some time to see if it will succeed later. Many times this kind of behavior is happening under the hood in libraries we use, such as Playwright.

There is a long list of different types of exceptions, such as the ValueError before, or a KeyError if a dictionary does not have the key you are attempting to access, or a TimeoutError which can occur if an operation times out due to some service not responding in time.

Loops

Loops in programming are constructs that allow developers to execute a block of code repeatedly, either a fixed number of times or until a certain condition is met. They are essential for automating repetitive tasks and iterating over collections of data. There are various types of loops, such as the for loop, which iterates over a range of values or elements in a collection, executing the specified code for each iteration; the while loop, which repeats a block of code as long as a given condition is true. Loops provide flexibility and efficiency in programming by allowing us to write concise and readable code for tasks that involve repetition, iteration, and traversal of data structures. They are fundamental constructs in nearly all programming languages and play a critical role in implementing algorithms, processing data, and controlling the flow of execution in software systems.

for

The for loop is used to iterate over a range of values or iterate over the elements in a list, tuple or set, etc. The syntax for for loops in Python is as follows:

Here we use the built-in function range that creates an iterator based on the number given as argument, in this case the function will return the numbers 0, 1, 2, 3 and 4 in order as the loop is iterated.

for i in range(5):
    print(i)
>>>0
>>>1
>>>2
>>>3
>>>4

Here we iterate over the elements in the list l.

l = [0, 1, 2, 3, 4]
for x in l:
    print(x)
>>>0
>>>1
>>>2
>>>3
>>>4

Test automation scripts may need to perform repetitive actions, such as clicking on multiple elements on a web page or entering data into multiple fields. Loops can be used to iterate over a list of elements or actions, executing the same steps for each item in the list.

while

The while loop can be used to run a block of code until the given condition is no longer met.

Here is a simple loop that will print "hello" for 3 seconds:

import time  # here we import the time module to have access to a function to get the current time in seconds

end_time = time.time() + 3  # our loop should end at this time; the current time + 3 seconds

while time.time() < end_time:  # we loop while current time is less than end_time
    print("hello")

This will simply print "hello" until the condition is False, which is after 3 seconds when time.time() returns a time that is after end_time.

Test automation scripts may use a while loop to wait for a certain condition, for example in web user interface testing, we could wait for a certain element to be present on a web page. This kind of waiting can happen implicitly within 3rd party library code, but sometimes waiting for conditions explicitly is still necessary.