assertRaises in python unit-test not catching the exception

user3014653 picture user3014653 · Jul 30, 2014 · Viewed 39.7k times · Source

Can somebody tell me why the following unit-test is failing on the ValueError in test_bad, rather than catching it with assertRaises and succeeding? I think I'm using the correct procedure and syntax, but the ValueError is not getting caught.

I'm using Python 2.7.5 on a linux box.

Here is the code …

import unittest

class IsOne(object):
    def __init__(self):
        pass
    def is_one(self, i):
        if (i != 1):
            raise ValueError

class IsOne_test(unittest.TestCase):

    def setUp(self):
        self.isone = IsOne()

    def test_good(self):
        self.isone.is_one(1)
        self.assertTrue(True)

    def test_bad(self):
        self.assertRaises(ValueError, self.isone.is_one(2))

if __name__ == "__main__":
    unittest.main()

and here is the output of the unit-test:

======================================================================
ERROR: test_bad (__main__.IsOne_test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test/raises.py", line 20, in test_bad
    self.assertRaises(ValueError, self.isone.is_one(2))
  File "test/raises.py", line 8, in is_one
    raise ValueError
ValueError

----------------------------------------------------------------------
Ran 2 tests in 0.008s

FAILED (errors=1)

Answer

Gerrat picture Gerrat · Jul 30, 2014

Unittest's assertRaises takes a callable and arguments, so in your case, you'd call it like:

self.assertRaises(ValueError, self.isone.is_one, 2)

If you prefer, as of Python2.7, you could also use it as a context manager like:

with self.assertRaises(ValueError):
    self.isone.is_one(2)