Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Wednesday, May 9, 2012

Python unit testing with doctest

I just learned that Python does unit testing pretty different compared to e.g. Java. They take an approach to inline the actual unit testing in the documentation string. By invoking doctest.testmethod() the magic starts. The tests also act as documentation at the same time which is pretty nice.
def fact(n):
   """
   >>> fact(0)
   1
   >>> fact(1)
   1
   >>> fact(4)
   24
   """   
   if n == 0:
       return 1
   else:
      return n * fact(n-1)

def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    _test()
When you run the above code no output gets printed as all tests pass fine. So let's screw up the code to see what happens if the tests fail.
def fact(n):
   """
   >>> fact(0)
   1
   >>> fact(1)
   1
   >>> fact(4)
   24
   """   
   if n == 0:
       return 0  # I falsly return 0 instead of 1 !!!
   else:
      return n * fact(n-1)

def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    _test()

**********************************************************************
File "t.py", line 3, in __main__.fact
Failed example:
    fact(0)
Expected:
    1
Got:
    0
**********************************************************************
File "t.py", line 5, in __main__.fact
Failed example:
    fact(1)
Expected:
    1
Got:
    0
**********************************************************************
File "t.py", line 7, in __main__.fact
Failed example:
    fact(4)
Expected:
    24
Got:
    0
**********************************************************************
1 items had failures:
   3 of   3 in __main__.fact
***Test Failed*** 3 failures.

No comments:

Post a Comment