Python中的单元测试接口

2024-10-02 04:24:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在学习python,为暑期的课程做准备,并且已经开始实现不同类型的堆和基于优先级的数据结构。在

我开始为这个项目编写一个单元测试套件,但是在创建一个只测试接口而忽略实际实现的通用单元测试时遇到了困难。在

我想知道是否有可能做这样的事。。在

suite = HeapTestSuite(BinaryHeap())
suite.run()
suite = HeapTestSuite(BinomialHeap())
suite.run()

我现在所做的只是感觉。。。错误(多重继承?确认!)。。在

^{pr2}$

Tags: 项目run数据结构类型套件错误单元测试课程
3条回答

为什么不为要测试的类使用别名呢?您可以编写引用伪HeapImpl类的测试类,然后在每次测试运行之前为其分配特定的实现:

class TestHeap(unittest.TestCase):
    def setUp(self):
        self.heap = HeapImpl()
    #test cases go here

if __name__ == '__main__'
    suite = unittest.TestLoader().loadTestsFromTestCase(TestHeap)
    heaps = [BinaryHeap, BinomialHeap]
    for heap in heaps:
        HeapImpl = heap
        unittest.TextTestRunner().run(suite)

只要它们符合您在测试套件中使用的接口,这应该可以正常工作。另外,您可以方便地测试任意多个实现,只需将它们添加到heaps列表中即可。在

我个人更喜欢这种东西。我会这样写:

# 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_')]

我不认为上述模式是可怕的,但多重继承肯定是不可取的。在

我想你不能让TestHeap成为TestCase的一个子类,是因为它将自动被提取并作为test运行,而不知道它需要被子类化。在

我用另外两种方法来解决这个问题:

  1. 不要添加test_u函数,而是让write方法不会自动被选中,然后将test()添加到每个子类中。显然不理想。在
  2. 重写unittest为not suck,允许将__test__ = False设置为基类。(见Testify

相关问题 更多 >

    热门问题