Python 如何使用unittest';s self.assertRaises是否在生成器对象中引发异常?

Python 如何使用unittest';s self.assertRaises是否在生成器对象中引发异常?,python,unit-testing,generator,Python,Unit Testing,Generator,我有一个要进行单元测试的生成器对象。它通过一个循环,当循环结束时某个变量仍然为0时,我会引发一个异常。我想测试一下,但我不知道怎么做。 以发电机为例: class Example(): def generatorExample(self): count = 0 for int in range(1,100): count += 1 yield count if count > 0:

我有一个要进行单元测试的生成器对象。它通过一个循环,当循环结束时某个变量仍然为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'
self.assertRaises(RuntimeError, lambda: list(Example().generatorExample()))
我想做的是

class testExample(unittest.TestCase):
    def test_generatorExample(self):
        self.assertRaises(RuntimeError, Example.generatorExample)
但是,生成器对象是不可伸缩的,因此

TypeError: 'generator' object is not callable
那么,如何测试生成器函数中是否引发异常?

是Python 2.7以来的上下文管理器,因此您可以这样做:

class testExample(unittest.TestCase):

    def test_generatorExample(self):
        with self.assertRaises(RuntimeError):
            list(Example().generatorExample())
如果您的Python<2.7,则可以使用
lambda
对生成器进行排气:

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'
self.assertRaises(RuntimeError, lambda: list(Example().generatorExample()))

谢谢,但如果可能的话,我必须在2.6中完成。我刚才用Python<2.7中的一个例子更新了我的答案。在2.6中,是否可以提取异常消息?@DanielMagnusson您可以手动完成,比如:
try:call();除了MyExcType作为e:self.assertEqual(e.message,“my msg”);异常除外,如ee:self.fail(“意外异常类型”);else:self.fail('应该抛出exc')
另一方面,我可以这样检查:
self.assertRaises(SomeException,SomeotherException,callable,*args,*kwargs)
?基本上,在一个调用中检查多个异常。