【问题标题】:How to use unittest's self.assertRaises with exceptions in a generator object?如何在生成器对象中使用 unittest 的 self.assertRaises 和异常?
【发布时间】:2012-03-24 20:53:39
【问题描述】:

我有一个想要进行单元测试的生成器对象。它经过一个循环,当循环结束时某个变量仍为 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

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

【问题讨论】:

    标签: python unit-testing generator


    【解决方案1】:

    assertRaises 从 Python 2.7 开始就是一个上下文管理器,所以你可以这样做:

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

    如果你有 Python lambda 来耗尽生成器:

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

    【讨论】:

    • 谢谢,但如果可能的话,我必须在 2.6 中这样做。
    • 我刚才已经更新了我的答案,举了一个例子,说明如何在 Python
    • 在 2.6 中是否可以提取异常消息?
    • @DanielMagnusson 您可以手动完成,例如:try: call(); except MyExcType as e: self.assertEqual(e.message, "my msg"); except Exception as ee: self.fail('Unexpected exception type'); else: self.fail('should have thrown an exc');
    • 另外,我可以这样检查:self.assertRaises(SomeException, SomeotherException, callable, *args, *kwargs)?基本上在一次调用中检查多个异常。
    猜你喜欢
    • 2012-04-18
    • 2019-03-18
    • 2018-12-05
    • 2020-12-03
    • 1970-01-01
    • 2019-11-07
    • 2019-10-18
    • 1970-01-01
    • 2013-11-20
    相关资源
    最近更新 更多