Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use unittest's self.assertRaises with exceptions in a generator object?

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?

like image 951
Niek de Klein Avatar asked Mar 07 '12 10:03

Niek de Klein


People also ask

How do I check if an exception is thrown in Python?

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.

What is assertRaises?

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.


1 Answers

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()))
like image 156
Jakub Roztocil Avatar answered Sep 29 '22 15:09

Jakub Roztocil