如何在生成器对象中使用unittest的self.assertRaises和异常?

2024-05-17 05:26:23 发布

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

我有一个生成器对象要进行单元测试。它经过一个循环,当循环结束时某个变量仍然为0时,我引发一个异常。我想联合测试,但我不知道怎么做。 以生成器为例:

class Example():
    def generatorExample(self):
        count = 0
        for int in range(1,100):
            count += 1
            yield count   
        if count > 0:
             raise RuntimeError, 'an example error that will always happen'

我想做的是

class testExample(unittest.TestCase):
    def test_generatorExample(self):
        self.assertRaises(RuntimeError, Example.generatorExample)

但是,生成器对象是不可计算的,因此

TypeError: 'generator' object is not callable

那么,如何测试生成器函数中是否引发异常?


Tags: 对象inselfforifexampledefcount
1条回答
网友
1楼 · 发布于 2024-05-17 05:26:23

^{}是Python 2.7之后的上下文管理器,因此您可以这样做:

class testExample(unittest.TestCase):

    def test_generatorExample(self):
        with self.assertRaises(RuntimeError):
            list(Example().generatorExample())

如果您有Python<;2.7,那么可以使用lambda来耗尽生成器:

self.assertRaises(RuntimeError, lambda: list(Example().generatorExample()))

相关问题 更多 >