Doctest in Python

Yang Zhou
TechToFreedom
Published in
3 min readAug 14, 2020

--

Doctest in Python
Photo by Hitesh Choudhary on Unsplash

Introduction

Doctest is a simple but useful testing method for Python programs. Compared with unit test, doctest doesn’t require an independent script to write test cases. Test cases can just be written in the doc information (contents within triple single/double quotes) of a Python function. Then these cases can test the function by using the doctest module.

The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown. (python document)

A Simple Example

Let’s use doctest for a wrong abs() function:

The result is as following:

A simple example of doctest
A simple example of doctest

As the above example shown, the doctest is really a convenient and simple way to test the function.

In a nutshell, there are just 3 steps:

  • import doctest module

--

--