Python > Testing in Python > Doctests > Running Doctests
Running Doctests in Python
doctest
module. Doctests are a simple and effective way to test your code by embedding example usages directly within docstrings. This makes your documentation executable and ensures that your code behaves as documented.
What are Doctests?
doctest
module then parses these docstrings, executes the embedded code, and verifies that the actual output matches the expected output you've provided. They are a lightweight way to test and document your code simultaneously.
Example Doctest
add
function with a docstring that includes doctests. The lines starting with >>>
represent the Python code to be executed. The line immediately following is the expected output. The if __name__ == '__main__':
block ensures that the doctests are run when the script is executed directly. doctest.testmod()
searches the current module for doctests and runs them.
def add(a, b):
"""Return the sum of a and b.
>>> add(2, 3)
5
>>> add(-1, 1)
0
>>> add(0, 0)
0
"""
return a + b
if __name__ == '__main__':
import doctest
doctest.testmod()
Running Doctests from the Command Line
python -m doctest
command followed by the name of your Python file. This is useful for automating tests as part of a build process or continuous integration setup.
python -m doctest your_module.py
Verbose Mode
-v
flag (verbose mode) provides more detailed output, showing each test case that is run and whether it passed or failed. This can be very helpful for debugging failing doctests.
python -m doctest -v your_module.py
Concepts Behind the Snippet
doctest
module provides the machinery to parse and execute these examples. It relies on string comparison to determine if the tests pass or fail. Therefore, output needs to be predictable.
Real-Life Use Case
Best Practices
-v
) during development to easily identify failing tests.pytest
or unittest
for more complex testing scenarios.
Interview Tip
When to Use Doctests
Memory Footprint
Alternatives
unittest
: Python's built-in unit testing framework, offering more advanced features like test suites, fixtures, and assertions.pytest
: A popular third-party testing framework that simplifies test discovery and execution.nose
: Another testing framework, though less actively maintained than pytest
.
Pros of Doctests
Cons of Doctests
FAQ
-
How do I handle exceptions in doctests?
You can include expected exceptions in your doctests using thedoctest.ELLIPSIS
flag, or by usingassertRaises
within the doctest itself. Refer to thedoctest
module's documentation for details. -
Can I ignore certain parts of the output in doctests?
Yes, you can use thedoctest.ELLIPSIS
flag to match variable parts of the output. This is useful for things like memory addresses or timestamps that change between runs.