1. Luke Plant
  2. sphinx


sphinx / doc / ext / doctest.rst

:mod:`sphinx.ext.doctest` -- Test snippets in the documentation

This extension allows you to test snippets in the documentation in a natural way. It works by collecting specially-marked up code blocks and running them as doctest tests.

Within one document, test code is partitioned in groups, where each group consists of:

  • zero or more setup code blocks (e.g. importing the module to test)
  • one or more test blocks

When building the docs with the doctest builder, groups are collected for each document and run one after the other, first executing setup code blocks, then the test blocks in the order they appear in the file.

There are two kinds of test blocks:

  • doctest-style blocks mimic interactive sessions by interleaving Python code (including the interpreter prompt) and output.
  • code-output-style blocks consist of an ordinary piece of Python code, and optionally, a piece of output for that code.

The doctest extension provides four directives. The group argument is interpreted as follows: if it is empty, the block is assigned to the group named default. If it is *, the block is assigned to all groups (including the default group). Otherwise, it must be a comma-separated list of group names.

The following is an example for the usage of the directives. The test via :dir:`doctest` and the test via :dir:`testcode` and :dir:`testoutput` are completely equivalent.

The parrot module

.. testsetup:: *

   import parrot

The parrot module is a module about parrots.

Doctest example:

.. doctest::

   >>> parrot.voom(3000)
   This parrot wouldn't voom if you put 3000 volts through it!

Test-Output example:

.. testcode::


This would output:

.. testoutput::

   This parrot wouldn't voom if you put 3000 volts through it!

There are also these config values for customizing the doctest extension: