Sitemap

Member-only story

Testing with Doctest in Python

--

In Python, testing is essential to ensure that your code behaves as expected. While frameworks like unittest and pytest are powerful, there's a simpler testing method available built right into the Python standard library: doctest.

It allows you to write tests directly in your documentation and can be particularly useful for small scripts, quick prototypes, or when you want to keep documentation and tests together. In this article, we’ll explore how doctest works, its use cases, advantages, and limitations.

Press enter or click to view image in full size

What is Doctest?

doctest is a module in Python that extracts and runs tests embedded in docstrings. It looks for Python interactive shell-like examples within the docstrings of functions, classes, and modules, and verifies that the output of the code matches the expected results. If the output matches, the test passes; otherwise, it fails.

Here’s an example:

def add(a, b):
"""
Adds two numbers together.

Example:
>>> add(2, 3)
5
"""
return a + b

In this case, doctest will run add(2, 3) and check if the result is 5.

There are two main ways to run the tests:

Using the doctest module directly in your script.

--

--