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.py168 chars14 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.py33 chars3 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.py31 chars2 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