🎓 A1Learner
🔍

Python Doctest

Doctest is a test written inside a docstring, in interactive style. Each example starts with >>> and shows the exact expected output.

A doctest in a docstring

The example looks like a copied interactive session.

def double(n):
    """
    >>> double(3)
    6
    """
    return n * 2

Count the results with testmod

testmod returns the counts of failed and attempted tests.

import doctest

def double(n):
    """
    >>> double(3)
    6
    >>> double(-1)
    -2
    """
    return n * 2

print(doctest.testmod())

Let part of the output vary with ELLIPSIS

The three dots stand for any text. Here they hide a changing code number.

import doctest

def greet(name):
    """
    >>> greet("Ana")  # doctest: +ELLIPSIS
    'Hello, Ana! Your code is ...'
    """
    return f"Hello, {name}! Your code is 4821"

print(doctest.testmod())

The interactive style

Printed text appears as itself. A value appears as its repr, with quotes for strings.

>>> print("hello")
hello
>>> 2 + 3
5

Example

import doctest

def slugify(text):
    """
    Turn a title into a URL-friendly slug.

    >>> slugify("Hello World")
    'hello-world'
    >>> slugify("Python Is Fun")
    'python-is-fun'
    >>> slugify("Already-Slugged")
    'already-slugged'
    >>> slugify("  Spaces  Everywhere  ")
    'spaces-everywhere'
    >>> slugify("")
    ''
    """
    words = text.lower().split()
    return "-".join(words)

if __name__ == "__main__":
    result = doctest.testmod()
    print(f"{result.failed} failed, {result.attempted} attempted")

Key points

  • Doctest: a test written inside a docstring, in interactive style.
  • Each example starts with >>> and the next line is the exact expected output.
  • Run doctests with python3 -m doctest file.py.
  • Silence means every example passed.
  • Use doctest.testmod() to run the doctests of a module from inside code.
  • Use the ELLIPSIS flag when part of the output may vary.
  • Doctest doubles as documentation that cannot quietly rot.
  • Doctest compares text exactly.

In this example, slugify turns a title into a slug. Its docstring holds five examples. Each example shows a call and the exact string it returns. The split call trims the extra spaces in the fourth example. The main block runs testmod and prints the two counts from the result. Zero failed means every docstring example still matches the code. You can also run python3 -m doctest on this file. It prints nothing, because nothing failed.

Note

A missing quote mark or an extra space counts as a failure.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

You run python3 -m doctest on a file and it prints nothing. What does that mean?