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?
assertRaises(exception, callable, *args, **kwds) Test that an exception (first argument) is raised when a function is called with any positional or keyword arguments. The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised.
assertraises is a function that fails unless an exception is raised by an object of a class. It is mostly used in testing scenarios to prevent our code from malfunctioning.
assertRaises
is a context manager since Python 2.7, so you can do it like this:
class testExample(unittest.TestCase):
def test_generatorExample(self):
with self.assertRaises(RuntimeError):
list(Example().generatorExample())
If you have Python < 2.7 then you can use a lambda
to exhaust the generator:
self.assertRaises(RuntimeError, lambda: list(Example().generatorExample()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With