doctesting practices

Alia Khouri alia_khouri at yahoo.com
Wed Aug 27 19:01:26 EDT 2008


I was wondering the other day how other pythonistas incorporate
doctests into their coding practices. I have acquired the habit of
keeping an editor open in one window and an ipython instance open in
another and then using something similar to the format of the module
below. In this case, I incorporate a switch in the _test function
whereby covered=False means the doctest is still being written (and is
easy to test using the command line) and covered=True means it is
somewhat complete and ready to be incorporated into a test suite.

This still seems to me to be somewhat hackish and convoluted (execing
into globals() and all), and one wonders if there are better coding
workflows out there that specifically incorporate doctests as the
primary means of testing.

Thanks in advance for any feedback

AK

</module>
'''
Simple doctest of a module

usage::

    >>> fib(0)
    0
    >>> fib(1)
    1
    >>> fib(10)
    55
    >>> fib(15)
    610

'''

def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)


def _test(covered=False):
    import doctest
    if covered:
        doctest.testmod()
    else:
        exec doctest.script_from_examples(__doc__) in globals()

if __name__ == '__main__':
    _test()

</module>





More information about the Python-list mailing list