[python] using doctest

doctests – looks on doc strings for usage specified like interactive python sessions. The main use of doctest is to update the docstrings as the implementation changes.

def say_hello(name=None):
    """A comment
    >>> say_hello()
    Hello
    >>> say_hello("Sathyz")
    Hello Sathyz
    >>> say_hello(1234)
    1234
    """
    from exceptions import TypeError
    if name is None:
        print "Hello"
    elif isinstance(name,str):
        print "Hello",name
    else:
        raise TypeError

if __name__=='__main__':
    import doctest
    doctest.testmod()
    print "Tests done" 

Executing this will give output like,

Z:\Spike\i-python>python say_hi.py
**********************************************************************
File "say_hi.py", line 7, in __main__.say_hello
Failed example:
    say_hello(1234)
Exception raised:
    Traceback (most recent call last):
      File "E:\Python25\lib\doctest.py", line 1228, in __run
        compileflags, 1) in test.globs
      File "", line 1, in 
        say_hello(1234)
      File "say_hi.py", line 16, in say_hello
        raise TypeError
    TypeError
**********************************************************************
1 items had failures:
   1 of   3 in __main__.say_hello
***Test Failed*** 1 failures.
Tests done
Z:\Spike\i-python>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s