Python Doctest or Docstring testing


One of the very usefull feature for unit testing the moduels written, as you know the importance of __name__ == "__main__"

How to test basic outputs of the simple function ? For eg. Fibonacci series with different Inputs like nagetive zero and some value like 2, 10, 100?
Solution is use Doctest module

Doctest will be included in python std lib.

How DOCTEST can be used ? (as given in http://docs.python.org/library/doctest.html )
  • To check that a module’s docstrings are up-to-date by verifying that all interactive examples still work as documented.
  • To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.
  • To write tutorial documentation for a package, liberally illustrated with input-output examples. Depending on whether the examples or the expository text are emphasized, this has the flavor of “literate testing” or “executable documentation”.
Here is an example for fibonacci

def fibo(n):
    """
    input: any integer
    output : fibonacci series

    This is docstrinf test
    >>> fibo(1)
    []
    >>> fibo(0)
    []
    >>> fibo(2)
    [1]
    >>> fibo(-1)
    []
    >>> fibo(-2)
    []
    >>> fibo(4)
    [1, 3, 5]
    >>> fibo(10)
    [1, 3, 5, 7, 9, 11, 13, 15, 17]
    >>>

    """
    fibo_lst = []
    for i in range(1,n):
        fibo_lst.append(i + i-1)
    print fibo_lst

if __name__ == "__main__":
    import doctest
    doctest.testmod()
To run doctest module with option "-v" eg. python doctst.py -v

Output :
python doctst.py -v
Trying:
fibo(1)
Expecting:
[]
ok
Trying:
fibo(0)
Expecting:
[]
ok
Trying:
fibo(2)
Expecting:
[1]
ok
Trying:
fibo(-1)
Expecting:
[]
ok
Trying:
fibo(-2)
Expecting:
[]
ok
Trying:
fibo(4)
Expecting:
[1, 3, 5]
ok
Trying:
fibo(10)
Expecting:
[1, 3, 5, 7, 9, 11, 13, 15, 17]
ok
1 items had no tests:
__main__
1 items passed all tests:
7 tests in __main__.fibo
7 tests in 2 items.
7 passed and 0 failed.
Test passed.