Introduction to doctest Module
Let's explore doctest module and how it can be useful.
We'll cover the following
Python includes a really useful module in its standard library that is
called doctest
. The doctest
module will look at our code and
determine if we have any text that looks like an interactive Python
session. Then doctest
will execute those given strings for testing to verify that they
work the way they are written.
According to the Python documentation, doctest
has three primary uses:
- Checking that a module’s docstrings are up-to-date by verifying the examples in the docstrings execute correctly
- Do regression testing using the interactive examples in the text or
- Write tutorial documentation for our package or module. We can do this by adding lots of examples in our docstrings that show inputs and outputs.
Creating a simple addition function
Let’s create a simple addition function that we can use to demonstrate what we can do with doctest
.
Save the following code into a file
named test.py
:
Get hands-on with 1400+ tech skills courses.