How to Use Doctest in Python ?
Here’s we will see how to use doctest in Python, here is a simple example of how to use doctest in Python.
1. import testmod from doctest to test the function.
2. Define our test function.
3. Provide a suitable docstring containing desired output on certain inputs.
4. Define the logic.
5. Call the testmod function with the name of the function to test and set verbose True as arguments.
Note: All the arguments are optional. The name of the function is explicitly passed to the testmod. It’s useful if there are multiple functions.
Implementation
In this example, below Python code tests the factorial
function using doctests. The function calculates the factorial of a positive number recursively. Docstrings define input and expected output. Running testmod
checks if the function behaves as expected for the provided test cases
# import testmod for testing our function
from doctest import testmod
# define a function to test
def factorial(n):
'''
This function calculates recursively and
returns the factorial of a positive number.
Define input and expected output:
>>> factorial(3)
6
>>> factorial(5)
120
'''
if n <= 1:
return 1
return n * factorial(n - 1)
# call the testmod function
if __name__ == '__main__':
testmod(name ='factorial', verbose = True)
Output:
Trying:
factorial(3)
Expecting:
6
ok
Trying:
factorial(5)
Expecting:
120
ok
1 items had no tests:
factorial
1 items passed all tests:
2 tests in factorial.factorial
2 tests in 2 items.
2 passed and 0 failed.
Test passed.
Now, test for failure.
Testing in Python using Doctest module
Docstrings in Python are used not only for the description of a class or a function to provide a better understanding of the code and use but, also used for Testing purposes. Testing is a critical aspect of software development that ensures code functions as expected and guards against bugs. In Python, the Doctest module provides a simple yet powerful way to test code by embedding test cases within docstrings.
Table of Content
- What is Doctest Module in Python
- Why Choose Doctest in Python?
- How to Use Doctest in Python?
- What if our Logic goes Wrong?
- Examples to Understand Doctest Module
- Limitations of Doctest module
- Frequently Asked Questions (FAQ’s)
Contact Us