pythontest automation

Python for test automation: built-in functions

Built-in functions in Python are pre-defined functions that are readily available for use without requiring explicit declaration or importing from external modules. These functions are built into the Python interpreter and cover a wide range of functionalities, including basic operations like input/output, data type conversion, mathematical operations, sequence manipulation, and more.

Here is a short list of some of most useful ones with test automation in mind:

  • sum: returns the sum of elements in an iterable
  • max: returns the maximum value from an iterable, or the maximum of multiple arguments
  • min: returns the minimum value from an iterable, or the minimum of multiple arguments
  • abs: returns the absolute value of a number
  • all: returns True if all elements of an iterable are true
  • any: returns True if any element of an iterable is true
  • enumerate: returns an enumerate object, containing index-value pairs of an iterable
  • len: returns the length of an object (e.g., string, list, tuple)

For a comprehensive list of all built-in functions, refer to the Python docs.

sum

sum simply returns the sum of the elements in an iterable given as the first argument to the function. There is a second, optional, argument defining the starting value for the sum: start. Here are examples to demonstrate basic usage of the function:

l = [1, 2, 3]
print(sum(l))
>>>6
print(sum(l, start=1))
>>>7

max and min

max takes in a variable amount of positional arguments, as well as a named argument key, which is a function defining how comparison between elements is done.

Here are a few examples to show how to use max:

print(max(1, 2))
>>>2
print(max([1, 2, 3]))
>>>3
dicts = [{"a": 1, "b": 2}, {"a": 3, "b": 1}]
# lambda determines which key of the dict is used for comparison
print(max(dicts, key=lambda d: d["a"]))
>>>{'a': 3, 'b': 1}

min is used exactly in the same way as max, except instead of returning the maximum value, the minimum value is returned.

abs

abs is short for absolute. It returns the absolute value, or distance from 0, of a given number.

print(abs(1))
>>>1
print(abs(-1))
>>>-1

all

all is a useful function in testing, since it provides a convenient way to check whether all elements in an iterable pass a condition or not. They are commonly used in conjunction with generator expressions: A generator expression in Python is a concise and memory-efficient way to create generator objects without the need for defining a separate generator function. It is similar to a list comprehension but produces values lazily, on-demand, as opposed to creating a list in memory. Generator expressions are defined within parentheses and consist of an expression followed by a 'for' loop, similar to list comprehensions. However, instead of constructing a list, they create a generator object that yields values one at a time when iterated over.

Here are a few examples on how to use the all function:

l = [1, 2, 3]
print(all(x > 0 for x in l))  # here 'x > 0 for x in l' is a
                              # generator expression that returns
                              # True or False based on evaluating
                              # ´x > 0' for each element at a time
>>>True  # since all the values are greater than 0, we see True

any

any is also a useful function in testing, since with it we can check whether at least one element in an iterable passes a condition or not. Using generator expression with any is also a common practice.

l = [-1, -2, 3]
print(all(x > 0 for x in l))
>>>True  # since the last value in the
         # list l is greater than 0, we see True

enumerate

The built-in function enumerate is used to iterate over a sequence while keeping track of the index of each item. It takes an iterable (such as a list, tuple, or string) as its argument and returns an enumerate object, which yields tuples containing both the index and the value of each item in the iterable. This allows for convenient access to both the index and the corresponding value during iteration. The enumerate function simplifies code by eliminating the need to manually manage index variables in loops. enumerate is commonly used with a for loop:

l = ["a", "b", "c"]
for i, x in enumerate(l):
    print(i, x)
>>>0 a
>>>1 b
>>>2 c

len

len is used to determine the length or the number of items in an object, such as a string, list, tuple, dictionary, or set. It takes a single argument, which can be any object that supports the length operation, and returns an integer representing the number of elements or characters in the object. The len function is commonly used to check the size of data structures, validate input lengths, or iterate over sequences using a dynamic range. len is also used as the key function in functions and methods such as max, min and sort.

l = [1, 2, 3]
print(len(l))
>>>3  # the list has 3 elements
l2 = [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
print(min(l2, key=len))  # minimum element based on length
>>>(1, 2)