Doctest

From CS 61A Wiki
Jump to: navigation, search

Doctest is a module in Python that looks for interactive sessions in strings called docstrings and then runs those sessions to see if the provided output matches the actual output. This module is useful both for debugging and for making sure that the examples in the documentation are correct.

Example

import math
 
def pythagoras(a, b):
    """
    Assuming that a and b are the two legs of a right triangle, calculates the length of the
    hypotenuse c using the formula c^2 = a^2 + b^2
 
    >>> pythagoras(3, 4)
    5.0
    >>> pythagoras(10, 11)
    14.866068747318506
    >>> pythagoras(0, 20) # This will catch an error in the code below
    Traceback (most recent call last):
        ...
    ValueError: The sides of a triangle must be positive.
    """
    if not (a >= 0 and b >= 0):
        raise ValueError("The sides of a triangle must be positive.")
    if a+1 == a or b+1 == b:
        raise OverflowError("The input(s) are too large")
    return math.sqrt(a ** 2 + b ** 2)
 
if __name__ == '__main__':
    import doctest
    doctest.testmod()

Now to see doctest work, one has to run the program just like any other program. Passed tests will not show up unless the -v verbose flag is used.

user:~$ python pythagoras.py -v
Trying:
    pythagoras(3, 4)
Expecting:
    5.0
ok
Trying:
    pythagoras(10, 11)
Expecting:
    14.866068747318506
ok
Trying:
    pythagoras(0, 20) # This will catch an error in the code below
Expecting:
    Traceback (most recent call last):
        ...
    ValueError: The sides of a triangle must be positive.
**********************************************************************
File "pythagoras.py", line 12, in __main__.pythagoras
Failed example:
    pythagoras(0, 20) # This will catch an error in the code below
Expected:
    Traceback (most recent call last):
        ...
    ValueError: The sides of a triangle must be positive.
Got:
    20.0
1 items had no tests:
    __main__
**********************************************************************
1 items had failures:
   1 of   3 in __main__.pythagoras
3 tests in 2 items.
2 passed and 1 failed.
***Test Failed*** 1 failures.

Command line interface

One can use the -m flag to run the doctest module on a Python file without having to import it in the code, and the -v option for more verbose output.

python -m doctest example.py
python -m doctest -v example.py


Sources