Thursday, June 7, 2007

Unit testing.. why wouldn't you?

Unit testing is a good thing, right? Especially if it is simple to set up, simple to run and simple to read the results. How do we do it in Python? Simple!
Here's a quick example using some pieces from the unit test file I checked in along with the python bitset:


import unittest
from pybitset import Bitset # import class or module under test

class bitset_testcase(unittest.TestCase):
def setUp(self): # testcase setup
self.bits = Bitset(10)

def testSize(self): # some method to test
# use assert to compare the expected and
# actual results
assert len(self.bits.bitstring)==self.bits.size(),
'Incorrect Size'

def testRepr(self): # some other method
assert self.bits.size() == len(self.bits.__repr__()),
'Repr size incorrect'


# .. if you need to test exceptions then write some code to
# provoke an exception and catch the exception and add an else
# clause to deal with exception failure

def testIndex(self):
try:
self.bits[40]=1
except IndexError:
pass
else:
self.fail("Out of range index expected exception")

# add the check for main so you can run from the command line
if __name__ == "__main__":
unittest.main()

Presto! Try it out, it's easy.

If you don't like my notes, go and read this

No comments: