Unit Testing Interfaces in Python
- by Nicholas Mancuso
I am currently learning python in preperation for a class over the summer and have gotten started by implementing different types of heaps and priority based data structures.
I began to write a unit test suite for the project but ran into difficulties into creating a generic unit test that only tests the interface and is oblivious of the actual implementation.
I am wondering if it is possible to do something like this..
suite = HeapTestSuite(BinaryHeap())
suite.run()
suite = HeapTestSuite(BinomialHeap())
suite.run()
What I am currently doing just feels... wrong (multiple inheritance? ACK!)..
class TestHeap:
def reset_heap(self):
self.heap = None
def test_insert(self):
self.reset_heap()
#test that insert doesnt throw an exception...
for x in self.inseq:
self.heap.insert(x)
def test_delete(self):
#assert we get the first value we put in
self.reset_heap()
self.heap.insert(5)
self.assertEquals(5, self.heap.delete_min())
#harder test. put in sequence in and check that it comes out right
self.reset_heap()
for x in self.inseq:
self.heap.insert(x)
for x in xrange(len(self.inseq)):
val = self.heap.delete_min()
self.assertEquals(val, x)
class BinaryHeapTest(TestHeap, unittest.TestCase):
def setUp(self):
self.inseq = range(99, -1, -1)
self.heap = BinaryHeap()
def reset_heap(self):
self.heap = BinaryHeap()
class BinomialHeapTest(TestHeap, unittest.TestCase):
def setUp(self):
self.inseq = range(99, -1, -1)
self.heap = BinomialHeap()
def reset_heap(self):
self.heap = BinomialHeap()
if __name__ == '__main__':
unittest.main()