I got a generator object that I want to unittest. It goes through a loop and, when at the end of the loop a certain variable is still 0 I raise an exception. I want to unittest this, but I don’t know how.
Take this example generator:
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'
What I would like to do is
class testExample(unittest.TestCase):
def test_generatorExample(self):
self.assertRaises(RuntimeError, Example.generatorExample)
However, a generator object isn’t calable and this gives
TypeError: 'generator' object is not callable
So how do you test if an exception is raised in a generator function?
assertRaisesis a context manager since Python 2.7, so you can do it like this:If you have Python < 2.7 then you can use a
lambdato exhaust the generator: