Are you tired of writing code snippets without testing them? Well, my friends, let me introduce you to the ‘doctest’ module your new best friend for testing Python code right within your scripts! This handy tool allows us to add comments and test cases directly into our code, making it easy to ensure that everything works as expected.
First, why should we bother with tests? Well, there are a few reasons. For one thing, they help us catch errors early on before they become bigger problems down the line. They also ensure consistency across different environments (because let’s face it, Python can be pretty finicky). And last but not least, they save us time and effort by allowing us to quickly identify and fix issues without having to manually test every single code snippet.
So how do we use ‘doctest’? First, you need to import the module at the top of your script:
# Import the doctest module to use its functionality
import doctest
# Define a function to calculate the area of a rectangle
def calculate_area(length, width):
"""
Calculates the area of a rectangle given its length and width.
Parameters:
length (int or float): The length of the rectangle.
width (int or float): The width of the rectangle.
Returns:
int or float: The area of the rectangle.
Examples:
>>> calculate_area(5, 10)
50
>>> calculate_area(2.5, 3.5)
8.75
"""
# Calculate the area by multiplying the length and width
area = length * width
# Return the area
return area
# Use doctest to automatically test the function and print the results
doctest.testmod()
# Output:
# TestResults(failed=0, attempted=2)
# Call the function with different inputs and print the results
print(calculate_area(5, 10))
print(calculate_area(2.5, 3.5))
# Output:
# 50
# 8.75
Now let’s say we have a function that calculates the factorial of a number. We can add comments within our code snippet that explain what each line does and include test cases to ensure it works as expected:
# Function to calculate the factorial of a number
def factorial(n):
"""Calculate the factorial of n"""
if n == 0 or n == 1: # Checks if n is equal to 0 or 1
return 1 # Returns 1 if n is 0 or 1
else:
result = 1 # Initializes result variable to 1
for i in range(2, n+1): # Loops through numbers from 2 to n+1
result *= i # Multiplies result by each number in the range
return result # Returns the final result
# Test cases
if __name__ == '__main__':
doctest.testfile('factorial_tests') # Runs doctest on the factorial_tests file to ensure the function works as expected
In this example, we’ve added a docstring to our function that explains what it does and included test cases within the script itself (using an if statement with the magic variable `__name__ == ‘__main__’`) by creating another file called ‘factorial_tests’. This file should contain examples of how to use your function, along with expected output:
# factorial_tests.py
"""Test cases for the factorial() function."""
# Import the factorial function from the main script
from factorial import factorial
# Define a function to test the factorial function with input 0
def test_zero():
# Use the assert statement to check if the output of factorial(0) is equal to 1
assert factorial(0) == 1
# Define a function to test the factorial function with input 1
def test_one():
# Use the assert statement to check if the output of factorial(1) is equal to 1
assert factorial(1) == 1
# Define a function to test the factorial function with input 5
def test_five():
# Use the assert statement to check if the output of factorial(5) is equal to 120
assert factorial(5) == 120
# The following code will only run if this script is executed directly, not if it is imported by another script
if __name__ == '__main__':
# Call the test functions to run the test cases
test_zero()
test_one()
test_five()
# Output:
# All tests passed!
Now, when you run your script (by executing it from the command line or using an IDE), ‘doctest’ will automatically detect and execute any examples within docstrings. If all tests pass, you’ll see a message saying “Test passed.” Otherwise, you’ll get a list of failed test cases with helpful error messages.