23.2.2 Simple Usage: Checking Examples in a Text File

Python 2.5

23.2.2 Simple Usage: Checking Examples in a Text File

Another simple application of doctest is testing interactive examples in a text file. This can be done with the testfile() function:

import doctest
doctest.testfile("example.txt")

That short script executes and verifies any interactive Python examples contained in the file example.txt. The file content is treated as if it were a single giant docstring; the file doesn't need to contain a Python program! For example, perhaps example.txt contains this:

The ``example`` module
======================

Using ``factorial``
-------------------

This is an example text file in reStructuredText format.  First import
``factorial`` from the ``example`` module:

    >>> from example import factorial

Now use it:

    >>> factorial(6)
    120

Running doctest.testfile("example.txt") then finds the error in this documentation:

File "./example.txt", line 14, in example.txt
Failed example:
    factorial(6)
Expected:
    120
Got:
    720

As with testmod(), testfile() won't display anything unless an example fails. If an example does fail, then the failing example(s) and the cause(s) of the failure(s) are printed to stdout, using the same format as testmod().

By default, testfile() looks for files in the calling module's directory. See section 23.2.4 for a description of the optional arguments that can be used to tell it to look for files in other locations.

Like testmod(), testfile()'s verbosity can be set with the -v command-line switch or with the optional keyword argument verbose.

For more information on testfile(), see section 23.2.4.

See About this document... for information on suggesting changes.