use the doctest module for testing in python

The doctest module allows you to write tests in the docstrings of your functions and modules. These tests are executed automatically when you run your Python script or module.

Here is an example of how to use doctest. Let's say you have a Python module called my_module:

main.py
def plus_one(x):
    """
    This function adds 1 to a number.

    >>> plus_one(1)
    2
    >>> plus_one(2)
    3
    >>> plus_one(0)
    1

    """
    return x + 1
168 chars
14 lines

The test cases are written as examples in the docstring. The syntax is the same as in the Python REPL.

You can then run the tests with the doctest module:

main.py
import doctest
doctest.testmod()
33 chars
3 lines

The testmod() function finds all the docstrings in the module and runs the tests. If a test fails, it raises an exception.

You can also run doctest from the command line like this:

main.py
python -m doctest my_module.py
31 chars
2 lines

This will run the tests in the my_module.py file.

doctest does have some limitations, and you may want to use the more full-featured unittest module for more complex tests. However, for simple tests and quick prototyping, doctest can be a useful tool.

gistlibby LogSnag