Lambda Lunacy: Unraveling the Mysteries of Python Lambdas for SDET Superstars!

Lambda Lunacy: Unraveling the Mysteries of Python Lambdas for SDET Superstars!

Discover the Power of Python Lambda Functions: From Simple Sorting to Advanced Test Automation Techniques

·

6 min read

TL;DR
Lambda functions, also known as anonymous functions, are a concise way to create small, one-time-use functions in Python. They are especially useful for SDETs (Software Development Engineers in Test) when writing test cases, as they can simplify code, make it more readable, and reduce the need for explicitly defining multiple small utility functions.

Level 1: Easy - Introduction to Lambda Functions

A lambda function is defined using the lambda keyword, followed by a list of arguments, a colon, and a single expression. The function can take any number of arguments but must return the result of only one expression. Lambda functions do not have a name, and they can be used wherever a function object is required.

For SDETs, lambda functions can be particularly helpful in situations such as sorting, filtering, or mapping data based on specific criteria. They are often used in conjunction with higher-order functions like sorted(), filter(), and map().

Syntax: lambda arguments: expression

Example 1.1 - Basic Lambda Function:

SDET Usecase

As an SDET, you might use lambda functions to sort test cases or filter test results. In this example, we have a list of test case durations, and we want to filter out the cases that took more than 5 seconds to run:

Example 1.2 - Filtering Test Cases:

Without a lambda function, you'd need to define a separate function for filtering:

Using a lambda function makes the code more concise and easier to understand.

Example 1.3 - Given a list of test case names, sort them alphabetically using a lambda function.

Level 2: Medium - Lambda Functions with Map and Reduce

Lambda functions can be combined with map() and reduce() to perform more complex operations.

Example 2.1 - Map with Lambda Function:

In this example, we convert a list of numeric test case IDs to strings with a prefix. Using a lambda function with map() is more concise than defining a separate function for the conversion.

Example 2.2 - Reduce with Lambda Function:

To use reduce(), you need to import it from the functools module.

In this example, we calculate the product of all numbers in a list using reduce() and a lambda function.

Example 2.3 -Given a list of test cases with durations, calculate the total duration using a lambda function and reduce().

In-depth explanation :

# Import the reduce function from the functools module
from functools import reduce

# Create a list of test durations (integers)
test_durations = [2, 6, 1, 7, 3, 8]

# Use the reduce function to sum the test durations by applying the lambda function (x + y) to each element in the list
# The reduce function takes two arguments: a function (in this case, a lambda function) and an iterable (test_durations)
# The lambda function adds two elements (x and y) together and returns the result
# The reduce function applies this lambda function cumulatively to the elements in the list, from left to right
# In this example, it will perform ((((2 + 6) + 1) + 7) + 3) + 8
total_duration = reduce(lambda x, y: x + y, test_durations)

# Print the total duration (the sum of all test durations)
print(total_duration)

Level 3: Hard - Advanced Lambda Functions and Real-World Scenarios

Lambda functions can be used for more complex tasks, like working with nested data structures or higher-order functions.

Example 3.1 - Lambda Function with Nested Data:

Suppose you have a list of test cases with their names, durations, and pass/fail statuses. You want to sort the test cases by duration.

In-depth explanation :

# Create a list of dictionaries, each representing a test case with its name, duration, and pass status
test_cases = [
    {"name": "test_login", "duration": 2, "passed": True},
    {"name": "test_signup", "duration": 6, "passed": False},
    {"name": "test_forgot_password", "duration": 1, "passed": True},
]

# Use the sorted function to sort the test_cases list of dictionaries
# The key parameter takes a function that computes a sort key for each element in the list
# In this case, a lambda function is used to return the value of the 'duration' key from each dictionary
# The sorted function will sort the list based on the 'duration' values in ascending order
sorted_test_cases = sorted(test_cases, key=lambda x: x["duration"])

# Print the sorted list of test cases
print(sorted_test_cases)

In this example, using a lambda function with the sorted() function is cleaner and more readable than defining a separate function for sorting.

SDET Usecase

As an SDET, you might encounter situations where you need to process and analyze test data in real-time. You could use a lambda function to create a custom reporting function that extracts specific information from your test results.

Example 3.2 - Custom Test Report:

In-depth explanation :

# Define a function called 'generate_report' that takes two parameters: 'test_data' and 'formatter'
def generate_report(test_data, formatter):
    # Iterate through each test in the 'test_data' list
    for test in test_data:
        # Call the 'formatter' function with the current test case as its argument, then print the result
        print(formatter(test))

# Define a function called 'format_test_result' that takes a single parameter: 'test'
def format_test_result(test):
    # Return a formatted string containing the test name, duration, and pass status (PASSED or FAILED)
    return f"{test['name']} - Duration: {test['duration']}s - {'PASSED' if test['passed'] else 'FAILED'}"

# Call the 'generate_report' function with the 'test_cases' list and a lambda function that wraps the 'format_test_result' function
generate_report(test_cases, lambda x: format_test_result(x))

In this example, we use a lambda function to pass a custom formatter to the generate_report() function. This allows us to create a flexible reporting system that can be customized easily.

Example 3.3 -Given a list of test cases with their names, durations, and pass/fail status, filter the test cases that failed, and then sort them by duration using lambda functions.

in-depth explanation :

# Create a list of dictionaries, each representing a test case with its name, duration, and pass status
test_cases = [
    {"name": "test_login", "duration": 2, "passed": True},
    {"name": "test_signup", "duration": 6, "passed": False},
    {"name": "test_forgot_password", "duration": 1, "passed": True},
]

# Use the filter function to create a new list containing only the dictionaries where "passed" is False
# The filter function takes two arguments: a function (in this case, a lambda function) and an iterable (test_cases)
# The lambda function returns True if the "passed" key's value is False, which means the dictionary will be included in the filtered list
failed_test_cases = list(filter(lambda x: not x["passed"], test_cases))

# Use the sorted function to sort the filtered list of dictionaries (failed_test_cases) based on the 'duration' key
# The key parameter takes a function that computes a sort key for each element in the list
# In this case, a lambda function is used to return the value of the 'duration' key from each dictionary
# The sorted function will sort the list based on the 'duration' values in ascending order
sorted_failed_test_cases = sorted(failed_test_cases, key=lambda x: x["duration"])

# Prints the response
print(sorted_failed_test_cases)

As you can see, we can easily leverage advanced Python concepts to make Test Automation frameworks more lightweight and robust. This also helps in our technical growth and development. Keep implementing various aspects of Python into your automation code.

Happy Coding!