The doctest module will search for pieces of text in your code that resemble interactive Python sessions. It will then execute those sessions to verify that they work exactly as written. This means that if you wrote an example in a docstring that showed the output with a trailing space or tab, then the actual output of the function has to have that trailing whitespace too. Most of the time, the docstring is where you will want to put your tests. The following aspects of doctest will be covered:

  • How to run doctest from the terminal
  • How to use doctest inside a module
  • How to run a doctest from a separate file

Let’s get started!

Running doctest via the Terminal

We will start by creating a really simple function that will double whatever is given to it. We will include a couple of tests inside the function’s docstring. Here’s the code (be sure and save it as "dtest1.py"):

Get hands-on with 1400+ tech skills courses.