Python doctest Module | Document and Test Code
As a developer, you know that writing code is just a small part of what it means to develop software. Once you’ve written your code, you need to test it to make sure it works as intended. One way to do that is to write unit tests. However, writing tests can be cumbersome, and you might forget to update them when the code changes. Luckily, Python provides a module that lets you document and test your code at the same time: the doctest
module.
What is the doctest
module?
The doctest
module provides a way to create tests for your code that are embedded in the documentation of your functions, classes, or modules. The tests are written using the same syntax as the interactive Python shell, and they can be run automatically as part of the documentation generation process. The doctest
module can be used to ensure that examples in your documentation stay up-to-date with the changes to the code.
Using the doctest
module will allow you to write tests that are:
- easy to write and understand
- embedded in the documentation
- automatically generated and run
How to Use doctest
Let’s see how you can use the doctest
module in Python to document and test your code. Let’s start by creating a function that adds two numbers:
def add_numbers(a, b):
"""
This function adds two numbers.
>>> add_numbers(2, 3)
5
>>> add_numbers(4, 4)
8
"""
return a + b
In this example, the documentation string of the add_numbers
function contains two examples of the function call, along with their expected output. The doctest
module will parse the documentation string, extract the examples, and run them as tests.
To run the tests, you can use the doctest.testmod()
function:
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)
When you run this script, the doctest
module will find the tests embedded in the documentation string and run them. If everything goes well, you won’t see any output. However, if a test fails, you’ll see an informative message that tells you what went wrong.
Using doctest
with classes
You can also use doctest
with classes. Let’s write a simple class that stores a list of numbers:
class NumberList:
"""
This class represents a list of numbers.
>>> numbers = NumberList()
>>> numbers.add_number(1)
>>> numbers.add_number(2)
>>> numbers.get_numbers()
[1, 2]
"""
def __init__(self):
self._numbers = []
def add_number(self, number):
self._numbers.append(number)
def get_numbers(self):
return self._numbers
In this example, the class NumberList
has two methods: add_number
and get_numbers
. The add_number
method adds a number to the list, and the get_numbers
method returns the list.
The documentation string of the class contains an example of creating an instance of the class, adding two numbers to the list, and then getting the list of numbers. The doctest
module will parse the documentation string, extract the example, and run it as a test.
To run the test, you can use the same doctest.testmod()
function as before.
doctest
Options
By default, doctest
runs all the tests it finds in the documentation string. However, there are some options you can use to control its behavior.
verbose
option
The verbose
option controls the level of detail printed when running the tests. By default, it is set to False
, which means that only failed tests will be printed. If you set it to True
, you’ll see more information about the tests, including which tests passed.
optionflags
option
The optionflags
option allows you to customize the way doctest
runs the tests. The most commonly used flags are:
doctest.NORMALIZE_WHITESPACE
: Allow strings to be compared with any amount of whitespace.doctest.ELLIPSIS
: Allow any substring of expected output, surrounded by...
, to match any substring of actual output.doctest.IGNORE_EXCEPTION_DETAIL
: Ignore the difference in exception details (such as file names and line numbers).
For example, if you want to allow any whitespace between words, you can set the optionflags
to doctest.NORMALIZE_WHITESPACE
:
if __name__ == '__main__':
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
Conclusion
The doctest
module is a simple and powerful tool for testing and documenting your Python code. By embedding tests in your documentation, you can ensure that your examples stay up-to-date with your code changes, and you can avoid the tedious work of writing and maintaining separate test files. With a little bit of effort, you can start using this module today to improve the quality of your Python code.