Jamie Cele Jamie Cele - 17 days ago 6
Python Question

Python unittest testcase on catching error failing

So I have class Dog:

class Dog:

def __init__(self, res):
self._res = res


def error(self):
raise IndexError


and unit test:

class TestDog(unittest.TestCase):

def setUp(self):
self.dog = Dog([1,2])

def testError(self):
self.assertRaises(IndexError, self.dog.error())


Why is the testcase testError failing? self.dog.error() should result in IndexError being rasied, and I believe the assertRaises is correctly formatted.

Any help is appreciated, thanks.

Answer

When Python runs the line self.assertRaises(IndexError, self.dog.error()), it has to calculate the arguments of the method self.assertRaises before passing them to it, so it calls self.dog.error() which raises an error. This is how all functions work. The presence of self.assertRaises does nothing to stop the error being raised. You are meant to call self.assertRaises(IndexError, self.dog.error), where the second argument is now the actual function/method object self.dog.error without having called it yet. self.assertRaises will call it for you wrapped in a try/except so that it can do the test properly.

Alternatively:

with self.assertRaises(IndexError):
    self.dog.error()
Comments