Python中的单元测试接口 [英] Unit Testing Interfaces in Python
问题描述
我目前正在为夏季的课程学习python,并且已经开始实施不同类型的堆和基于优先级的数据结构。
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()
推荐答案
我个人喜欢鼻子测试生成更多这类事情。然后我会写它:
I personally like nose test generation more for this sort of thing. I'd then write it like:
# They happen to all be simple callable factories, if they weren't you could put
# a function in here:
make_heaps = [BinaryHeap, BinomialHeap]
def test_heaps():
for make_heap in make_heaps:
for checker in checkers: # we'll set checkers later
yield checker, make_heap
def check_insert(make_heap):
heap = make_heap()
for x in range(99, -1, -1):
heap.insert(x)
# def check_delete_min etc.
checkers = [
value
for name, value in sorted(globals().items())
if name.startswith('check_')]
这篇关于Python中的单元测试接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!