Friday, June 28, 2013

Python assertRaises exception inside generator

So I have a generator and I want to make sure it throws an exception after a certain number of calls. So expected behaviour is this:
def generate():
    yield 1
    yield 2
    raise Exception()
How do you check that in a test? You can't do this:
class testExample(unittest.TestCase):
    def test_generatorExample(self):
        self.assertRaises(Exception, a)
since a generator isn't callable. Turns out that assertRaises is a context manager as of python 2.7, which is very cool:
class testExample(unittest.TestCase):
    def test_generatorExample(self):
        with self.assertRaises(Exception):
            list(a)
Or for earlier versions of python you could use a lambda:
self.assertRaises(Exception, lambda: list(a))

No comments: