DocTests


Testing is the process of running experiments to verify that parts of your program are doing what they are supposed to. As you can imagine, testing is a critical skill in programming. There are many ways to test -- one way is to use appropriate print statements. Functions which take in parameters and return values can be directly tested using a feature called a "doctest".

A doctest is a special command that is written in the comment at the start of a function definition. It allows you to specify what outputs you expect for a certain input. For example imagine we have a function is_divisible which tests if a first parameter is devisitible by a secton. If you pass in 20, 10 this function should return True. We can write a doctest by typing >>> followed by a call to our function. On the next line you should write the value which is being returned.

"""
>>> is_divisible(20, 10)
True
"""

Here is a more complete example!

"""
Example of using the index variable of a for loop
"""

def main():
    pass

def is_divisible(a, b):
    """
    >>> is_divisible(20, 4)
    True
    >>> is_divisible(12, 7)
    False
    >>> is_divisible(10, 10)
    True
    """
    return a % b == 0

def is_leap_year(year):
    """
    Returns Boolean indicating if given year is a leap year.
    It is a leap year if the year is:
    * divisible by 4, but not divisible by 100
     OR
    * divisible by 400
    Doctests:
    >>> is_leap_year(2001)
    False
    >>> is_leap_year(2020)
    True
    >>> is_leap_year(2000)
    True
    >>> is_leap_year(1900)
    False
    """

    # if the year is divisible by 400, it is a leap year!
    if is_divisible(year, 400):
        return True

    # other wise its a leap year if its divisible by 4 and not 100
    return is_divisible(year, 4) and not is_divisible(year, 100)

Running doctests

You can run doc tests by executing the doctest python module:

python -m doctest leap_year.py -v

This will run all the tests in leap_year.py to run the doc tests in another file you would write that file name in place of leap_year.py.